Связывание DP Control2 с DP Control1 в WPF - PullRequest
0 голосов
/ 11 октября 2018

У меня есть два простых UserControls.Оба имеют свойство зависимости, называемое Value.Теперь в моем главном окне я использую элементы управления и пытаюсь привязать значение одного к значению другого!К сожалению, он работает только в первый раз и не обновляется после изменения значения в control1.

Control1:

<UserControl x:Class="ControlBining.Control1"
             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="450" d:DesignWidth="800">
    <Grid>
        <TextBox Text="{Binding Value, RelativeSource={RelativeSource AncestorType=UserControl}}" Width="100"/>
    </Grid>
</UserControl>

  public static readonly DependencyProperty ValueProperty =
     DependencyProperty.Register(
        "Value", typeof(string),
        typeof(Control1)
     );

  public string Value
  {
     get => (string)GetValue(ValueProperty);
     set => SetValue(ValueProperty, value);
  }

Control2:

<UserControl x:Class="ControlBining.Control2"
             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" 
             xmlns:local="clr-namespace:ControlBining"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <TextBlock Text="{Binding Value, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </Grid>
</UserControl>

  public static readonly DependencyProperty ValueProperty =
     DependencyProperty.Register(
        "Value", typeof(string),
        typeof(Control2)
     );

  public string Value
  {
     get => (string)GetValue(ValueProperty);
     set => SetValue(ValueProperty, value);
  }

Главное окно:

<Window x:Class="ControlBining.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ControlBining"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <local:Control1 Width="100" x:Name="Control1" Value="10"/>
        <local:Control2 Width="100" Value="{Binding ElementName=Control1, Path=Value}"/>
    </StackPanel>
</Window>

1 Ответ

0 голосов
/ 11 октября 2018

UserControl не должен устанавливать свой собственный DataContext, потому что это нарушает любые привязки на основе DataContext его свойств зависимостей.Вместо этого используйте привязку RelativeSource в ее XAML:

<UserControl ...>
    <Grid>
        <TextBox Text="{Binding Value,
                        RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </Grid>
</UserControl>

Если вы хотите обновить свойство Value во время ввода в TextBox, также установите следующее:

<TextBox Text="{Binding Value,
                RelativeSource={RelativeSource AncestorType=UserControl},
                UpdateSourceTrigger=PropertyChanged}"/>

Если вы также хотите ввести в Control2, сделайте привязку значения TwoWay:

<local:Control2 Value="{Binding ElementName=Control1, Path=Value, Mode=TwoWay}"/>

или сделайте свойство Value связывать TwoWay по умолчанию:

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register(
        nameof(Value), typeof(string), typeof(Control2),
        new FrameworkPropertyMetadata(
            null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
...