绑定值未传递给WPF中的用户控件
我看起来很长很难,而且卡住了。 我正在尝试通过Window中的绑定将参数从Window传递给UserControl1。
在MainWindow中,UserControl1包含两次,一次通过MyValue上的绑定传递参数MyCustom,再次使用文字。 使用绑定传递对UserControl1没有影响。 MyCustom依赖项属性未更改。 使用文字,它按预期工作。
我很困惑。 我在https://stackoverflow.com/a/21718694/468523中复制了这个例子,但没有快乐。 必须有一些我想念的简单。
对于我复制的所有代码感到很抱歉,但魔鬼经常在细节中。
MainWindow.xaml
MainWindow.xaml.cs
namespace MyParamaterizedTest3 { public partial class MainWindow : INotifyPropertyChanged { public MainWindow() { InitializeComponent(); } public string MyValue { get => _myValue; set => SetField(ref _myValue, value); } private string _myValue= "First things first"; public event PropertyChangedEventHandler PropertyChanged; protected bool SetField(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer.Default.Equals(field, value)) { return false; } field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); return true; } } }
UserControl1.xaml(在下面更正)
UserControl1.xaml.cs(以下更正)
namespace MyParamaterizedTest3 { public partial class UserControl1 : INotifyPropertyChanged { public UserControl1() { InitializeComponent(); } public static readonly DependencyProperty MyCustomProperty = DependencyProperty.Register("MyCustom", typeof(string), typeof(UserControl1)); public string MyCustom { get { return this.GetValue(MyCustomProperty) as string; } set { this.SetValue(MyCustomProperty, value); } } public event PropertyChangedEventHandler PropertyChanged; protected bool SetField(ref T field, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer.Default.Equals(field, value)) { return false; } field = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); return true; } } }
更正了UserControl1.xaml(每个Ed Plunkett)
更正了UserControl1.xaml.cs(每个Ed Plunkett)
在XAML窗口中,默认情况下,usercontrol实例上的绑定使用usercontrol的DataContext作为其源。 你假设它从窗口inheritance了它的datacontext。
但这是UserControl中的这个:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
这会打破父母赋予它的所有绑定。 所以不要这样做。 使用relativesource:
也:
-
UpdateSourceTrigger=PropertyChanged
对于从不更新其源的属性的绑定不起任何作用,因此可以省略。 -
正如我们在注释中讨论的那样,依赖属性不需要
INotifyPropertyChanged
。 -
当绑定不起作用时,这是非常令人沮丧的,因为你如何调试它们? 你看不到任何东西。 关键是它在哪里寻找这个属性? 您可以获得如下诊断信息:
这将在运行时向Visual Studio的“输出”窗格发出大量调试信息。 它将告诉你Binding正在尝试做什么,一步一步,它找到了什么,以及它失败的地方。
-
该窗口可以将自己的DataContext设置为Self,因为它没有父级,因此它不会踩到inheritance的DataContext。 但是,窗口可以并且应该使用RelativeSource本身 – 或者更好的是,编写一个主viewmodel类(您知道如何实现INPC),将窗口的属性移动到主视图模型,并将viewmodel的实例分配给窗口的DataContext的。