依赖属性未更新我的用户控件

14

下面的代码适用于继承自INotifyPropertychanged类的属性CellNo,作用于TextBox DP Text。因此当我更改CellNo时,Text将被更新,这将很好地实现。

Text="{Binding Path = CellNo, Mode=TwoWay,  UpdateSourceTrigger=PropertyChanged}"

我创建了一个只包含一个文本框的用户控件。我定义了一个名为CellValue的DP,如下所示:

public string CellValue
    {
        get { return (string)GetValue(CellValueProperty); }
        set { SetValue(CellValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for LimitValue.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CellValueProperty =
        DependencyProperty.Register("CellValue", typeof(string), typeof(control), new FrameworkPropertyMetadata
        {
            BindsTwoWayByDefault = true,
        });

当我在任何对话框中使用这个用户控件并进行与上述相同的绑定时,目标(用户控件内的文本框)不会更新。

 <local:control
        x:Name="control" 
        CellValue="{Binding Path = CellNo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

我也在用户控件内将文本框的Text属性绑定到CellValue DP。

用户控件内部

<TextBox                 
        Text="{Binding Path = CellValue}"
        Name="textBox2" />
我希望当CellValue改变时,TextBox Text也会被更新,但是使用上述方法后,它仍然为空白。

1
您能看到输出窗口中是否有任何数据绑定错误?用户控件的 DataCcontext 属性是否设置正确,以使 TextBox 绑定有效? - Gishu
是的,用户控件的数据上下文与父控件相同。同时在调试时,我验证了依赖属性(CellValue)在用户控件内部更新,但它没有更新TexBox的Text属性。我需要实现Property changed回调吗? - Ashish Ashu
1个回答

18
这段代码。
<local:control x:Name="control"  
               CellValue="{Binding Path=CellNo,
                                   Mode=TwoWay,
                                   UpdateSourceTrigger=PropertyChanged}">

正在尝试绑定到UserControl的Property CellNo。添加RelativeSource或ElementName,它就可以工作。

<local:control x:Name="control"  
               CellValue="{Binding Path=CellNo,
                                   RelativeSource={RelativeSource AncestorType={x:Type Window}}, 
                                   Mode=TwoWay,
                                   UpdateSourceTrigger=PropertyChanged}">

<local:control x:Name="control"  
               CellValue="{Binding Path=CellNo,
                                   ElementName=myWindow,
                                   Mode=TwoWay,
                                   UpdateSourceTrigger=PropertyChanged}">

您可能还需要将控件的DataContext设置为其本身。

public control()
{
    InitializeComponent();
    this.DataContext = this;
    //...
}

更新

您可以从这里下载此示例应用程序。

否则,这是完整的示例代码。

MainWindow.xaml

<Window x:Class="DependencyPropertyInsideUserControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DependencyPropertyInsideUserControl"
        Title="MainWindow" Height="350" Width="525"
        Name="myWindow">
    <Grid>
        <local:control x:Name="control"
                       CellValue="{Binding Path = CellNo, Mode=TwoWay, ElementName=myWindow, UpdateSourceTrigger=PropertyChanged}"/>
            <Button Content="Update CellNo" Height="23" HorizontalAlignment="Left" Margin="185,149,0,0" Name="button1" VerticalAlignment="Top" Width="94" Click="button1_Click" />
    </Grid>
</Window>

主窗口.xaml.cs

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        CellNo = "Hello";
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        CellNo = "Hi";
    }
    private string m_cellNo;
    public string CellNo
    {
        get
        {
            return m_cellNo;
        }
        set
        {
            m_cellNo = value;
            OnPropertyChanged("CellNo");
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

control.xaml

<UserControl x:Class="DependencyPropertyInsideUserControl.control"
             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>
        <TextBox Text="{Binding Path = CellValue}" 
                 Name="textBox2" />
    </Grid>
</UserControl>

control.xaml.cs

public partial class control : UserControl
{
    public string CellValue
    {
        get { return (string)GetValue(CellValueProperty); }
        set { SetValue(CellValueProperty, value); }
    }
    // Using a DependencyProperty as the backing store for LimitValue.  This enables animation, styling, binding, etc...    
    public static readonly DependencyProperty CellValueProperty =
        DependencyProperty.Register("CellValue", typeof(string), typeof(control), new FrameworkPropertyMetadata
        {
            BindsTwoWayByDefault = true,
        });
    public control()
    {
        InitializeComponent();
        this.DataContext = this;
        CellValue = "Test";
    }
}

3
我必须在窗口中使用“Path=DataContext.CellNo”才能使绑定对我起作用。 - Dan Vogel
在设计时,您是否可以看到UserControl中的DefaultValue? - Dominic Jonas
在我的情况下,在MainWindow上使用MVVM模式,我不得不在控件代码中设置textBox2.DataContext = this;而不是this.DataContext = this,否则它会破坏MVVM绑定。 - CowWarrior

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接