【发布时间】:2017-04-04 17:45:37
【问题描述】:
所以我尝试了所有我知道如何绑定数据的方法,但我似乎无法让我的属性更改事件正确绑定
我有一个简单的用户控件,其背后的代码如下:
public partial class EnableForms : INotifyPropertyChanged
{
private GenericViewData _thisGenericViewData;
public GenericViewData ThisGenericViewData
{
get { return _thisGenericViewData; }
set
{
_thisGenericViewData = value;
OnPropertyChanged();
}
}
public EnableForms()
{
InitializeComponent();
//DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
视图是以下 XAML:
<UserControl x:Class="namespace.EnableForms"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+
xmlns:local="clr-namespace:viewNamespace"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
DataContext="{Binding RelativeSource={RelativeSource self}}">
<!--d:DesignHeight="300" d:DesignWidth="300">-->
<Grid>
<TextBlock Text="{Binding Source=ThisGenericViewData}"></TextBlock>
<!-- <TextBlock Text="{Binding ThisGenericViewData, RelativeSource={RelativeSource AncestorType={x:Type local:EnableForms}}}" /> -->
</Grid>
使用一些旧的导航逻辑,我创建了视图并因此导航到它:
MainWindow.WindowControlHost.Navigate(new viewNamespace.EnableForms
{
ThisGenericViewData = viewData
});
我知道导航逻辑工作正常,我可以看到 ThisGenericViewData 被设置为有效数据。我的问题是,在我的代码后面,propertychanged 事件从未设置,它始终为空。
我已经尝试在将数据上下文设置为此 (DataContext = this) 的代码中,但这也不起作用。我尝试在文本块中对 self 进行相对绑定,但它也不起作用。我知道它正在竞标到正确的源,因为我可以右键单击并转到源(使用相对绑定时)并导航到该属性。
有人可以说明一下情况并告诉我我做错了什么
【问题讨论】:
-
DataContext="{Binding RelativeSource={RelativeSource self}}"没有什么好处。将用户控件绑定到自身会导致各种奇怪的行为。 -
即使我把它拿出来并在初始化组件之后的代码中执行它,我也会得到相同的结果。
-
使用此答案的第二部分:Another Answer 我添加了一个名称,并且绑定神奇地起作用了。为什么这会有所不同?
-
你试过
Binding .作为你的DataContext吗?
标签: c# wpf xaml data-binding