【问题标题】:wpf mvvm with non dependency properties?wpf mvvm 具有非依赖属性?
【发布时间】:2013-06-20 13:14:45
【问题描述】:

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

【问题讨论】:

  • 您需要仅通过虚拟机设置SelectedText,还是必须双向进行绑定?
  • 好的,我会给你一个解决方案。
  • 你可以创建一个你可以在你的虚拟机中绑定的行为

标签: wpf mvvm


【解决方案1】:

如果您只需要从 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}" />

【讨论】:

  • 只是出于好奇:为什么要添加一个引发异常的失败检查,以防止让 c# 引发异常?对我来说,似乎唯一的原因是使用 ArgumentNullException 而不是 NullReferenceException,但要以编写更多代码为代价,但使用适当的 IDE 甚至只是调用堆栈,它应该是显而易见的。
  • 既然方法是公开的,您应该始终以这种或类似的方式实现它,以便它可以正确运行。至少这是我多年来学到的东西。恕我直言,应该始终这样做,因为您不知道将来谁在使用此方法,并且您不知道他如何尝试使用它。因此,您可以通过让代码引发 NullReferenceException 或引发更具体和有意的异常来进入未定义状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 2015-02-03
  • 2014-05-23
相关资源
最近更新 更多