因此,我已经尝试了所有我知道如何数据绑定的方法,但我似乎无法让我的属性更改事件正确绑定
我有一个简单的用户控件,后面的代码如下:
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被设置为有效数据。我的问题是,在我后面的代码中,属性更改事件永远不会被设置,它始终是空的。
我尝试过将数据文本设置为这个(DataContext = this
)的代码,但这也不起作用。我尝试过在文本块中对self进行相对绑定,但是它也不起作用。我知道它正在等待正确的源,因为我可以右键单击并转到源代码(当使用相对绑定时),它导航到属性。
谁能帮我弄清楚情况,告诉我我做错了什么
发布于 2017-04-04 18:15:33
使用this answer,提到元素名,用户认为是对自己进行数据绑定的更好方法。这就是对我起作用的东西。只更改XAML现在看起来如下所示
<UserControl x:Class="viewNamespace.EnableForms"
Name="EnableFormsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
>
<!--d:DesignHeight="300" d:DesignWidth="300">-->
<Grid>
<TextBlock Text ="{Binding ThisGenericViewData, ElementName=EnableFormsView}" />
</Grid>
发布于 2017-04-04 20:44:00
您应该将Binding
的Path (而不是Source)属性设置为"ThisGenericViewData":
<TextBlock Text="{Binding Path=ThisGenericViewData}"></TextBlock>
如果您将DataContext
的UserControl设置为它自己,这应该是可行的:
DataContext="{Binding RelativeSource={RelativeSource self}}"
路径指定要绑定到的属性的名称,源指定定义该属性的源对象。
https://stackoverflow.com/questions/43214161
复制相似问题