设置数据上下文后,PropertyChanged事件为null

时间:2017-04-04 17:45:37

标签: c# wpf xaml data-binding

所以我已经尝试了所有我知道如何数据绑定的方法,但我似乎无法让我的属性更改事件正确绑定

我有一个简单的用户控件,后面的代码如下:

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事件,它始终为null。

我已经尝试将datacontext设置为此(DataContext = this),但这也不起作用。我已尝试在文本块中对self进行相对绑定,但它也不起作用。我知道这是正确的来源,因为我可以右键单击并转到源(当使用相对绑定时),它导航到属性。

有人可以对情况有所了解并告诉我我做错了什么

2 个答案:

答案 0 :(得分:1)

您应该将Binding Path (而不是 Source )属性设置为&#34; ThisGenericViewData&#34;:

<TextBlock Text="{Binding Path=ThisGenericViewData}"></TextBlock>

如果您将UserControl的DataContext设置为自身,那么这应该可以工作:

DataContext="{Binding RelativeSource={RelativeSource self}}"

Path指定要绑定的属性的名称,source指定定义该属性的源对象。

答案 1 :(得分:0)

使用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>