微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

wpf mvvm具有非依赖属性?

我有一个小(我希望)的问题.我有一个wpf项目,我使用MVVM,但我需要设置文本框的“SelectedText”属性. “selectedText”不是依赖属性,所以我不能使用绑定…
我怎么解决这个问题?

解决方法

如果您只需要从VM到控件的值赋值,则可以使用这样的AttachedProperty.

public class AttachedProperties
{
    private static DependencyProperty SelectedTextProperty =
        DependencyProperty.Registerattached("SelectedText",typeof(string),typeof(AttachedProperties),new PropertyMetadata(default(string),OnSelectedTextChanged)));

     private static void OnSelectedTextChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
     {
         var txtBox = d as TextBox;
         if (txtBox == null)
             return;

         txtBox.SelectedText = e.NewValue.ToString();
     }

     public static string GetSelectedText(DependencyObject dp)
     {
         if (dp == null) throw new ArgumentNullException("dp");

         return (string)dp.GetValue(SelectedTextProperty);
     }

     public static void SetSelectedText(DependencyObject dp,object value)
     {
         if (dp == null) throw new ArgumentNullException("dp");

         dp.SetValue(SelectedTextProperty,value);
     }
}

用法

<!-- Pls note,that in the Binding the property 'SelectedText' on the VM is refered -->
<TextBox someNs:AttachedProperties.SelectedText="{Binding SelectedText}" />

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐