Подтвердить что ты не робот

Свойство Dependency не обновляет мой Usercontrol

Строка ниже работает для TextBox DP Текст, где CellNo является свойством класса, который происходит из INotifyPropertychanged. Поэтому здесь, когда я меняю CellNo, текст будет обновляться, и когда я изменю CellNo, текст будет обновлен. Это будет нормально работать.

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

Я создал пользовательский элемент управления, который содержит только один TextBox. Я определил одно имя DP CellValue, как показано ниже:

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,
        });

Теперь, когда я использую этот элемент управления пользователя в любом диалоговом окне и выполняю ту же привязку, что и выше, Target (TextBox внутри User control) НЕ обновляется.

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

Также внутри пользовательского элемента управления я привязал текстовое свойство TextBox к CellValue DP.

Внутренний контроль пользователя

<TextBox                 
        Text="{Binding Path = CellValue}"
        Name="textBox2" />

Я хочу, чтобы изменения CellValue TextBox Text также были обновлены, но с приведенным выше приложением он остается пустым.

4b9b3361

Ответ 1

Этот код

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

пытается связать с Property CellNo в UserControl. Добавьте 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>

MainWindow.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";
    }
}