wpf mvvm具有非依赖属性?

Ser*_*giu 6 wpf mvvm

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

DHN*_*DHN 9

如果您只需要从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);
     }
}
Run Code Online (Sandbox Code Playgroud)

和用法

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

  • 因为该方法是公共的,所以您应该始终以相同或类似的方式实现它,以便它可以正确运行.至少这是我多年来学到的东西.恕我直言,它应该总是这样做,因为你不知道,将来谁在使用这种方法,你不知道他是如何使用它的.因此,您可以通过让代码引发`NullReferenceException`或者引发更具体和有意的异常来进入未定义状态. (2认同)