Как связать свойство родительского элемента со свойствами дочерних элементов usercontrol - PullRequest
1 голос
/ 19 марта 2019

Мне нужно связать свойство Text текстового поля в моем окне со свойствами текста текстовых полей в дочернем usercontrol.BeloW - это код, который я пробовал, но он не работал должным образом.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
   <Grid>
      <Grid.RowDefinitions>
          <RowDefinition/>
          <RowDefinition/>
      </Grid.RowDefinitions>
      <TextBox Width="150" HorizontalAlignment="Center" 
       VerticalAlignment="Center">
      <TextBox.Text>
            <MultiBinding StringFormat=" {0} {1}}">
                <Binding Path="txtF.Text" RelativeSource="{RelativeSource 
                   Mode=FindAncestor, AncestorType={x:Type UserControl}}"/>
                <Binding Path="txtl.Text"  RelativeSource="{RelativeSource 
                   Mode=FindAncestor, AncestorType={x:Type UserControl}}"/>
            </MultiBinding>
      </TextBox.Text>
    </TextBox>
   <uc:UserControl1 x:Name="SomeUC"  Grid.Row="1" 
       HorizontalAlignment="Center" VerticalAlignment="Top"/>
   </Grid>
 </Window>
 <UserControl x:Class="WpfApplication1.UserControl1"
         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>
    <StackPanel Orientation="Horizontal">
        <TextBox x:Name="txtF" Width="120" Height="20" Margin="5"/>
        <TextBox  x:Name="txtL" Width="120" Height="20"/>
    </StackPanel>
</Grid>
</UserControl>

Любая помощь будетбыть высоко оценен.Спасибо

1 Ответ

2 голосов
/ 19 марта 2019

Вы не можете получить доступ к txtF и txtL по имени, поскольку текстовые поля внутри UserControl находятся в другой области имен. Проверьте эту ссылку для получения дополнительной информации об областях именования WPF.

Самый простой способ сделать это, вероятно, состоит в том, чтобы добавить свойство TextCombined в ваш usercontrol, установить его, когда один из TextBoxes изменит свой текст, и привязать его к вашему окну:

Код позади вашего UserControl:

public partial class UserControl1 : UserControl
{
    public static readonly DependencyProperty TextCombinedProperty =
        DependencyProperty.Register("TextCombined", typeof(string),
            typeof(UserControl1), new PropertyMetadata(String.Empty));

    public string TextCombined
    {
        get { return (string)GetValue(TextCombinedProperty); }
        set { SetValue(TextCombinedProperty, value); }
    }

    public UserControl1()
    {
        InitializeComponent();
        txtF.TextChanged += OnTextFieldTextChanged;
        txtL.TextChanged += OnTextFieldTextChanged;
    }

    private void OnTextFieldTextChanged(object _, TextChangedEventArgs __)
    {
        SetCurrentValue(TextCombinedProperty, $"{txtF.Text} {txtL.Text}");
    }
}

Окно XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBox Width="150" 
             HorizontalAlignment="Center" 
             VerticalAlignment="Center"
             Text="{Binding ElementName=SomeUC, Path=TextCombined}" />

    <local:UserControl1 x:Name="SomeUC"
                        Grid.Row="1" 
                        HorizontalAlignment="Center"
                        VerticalAlignment="Top"/>
</Grid>

UserControl XAML менять не нужно. Надеюсь, что это работает для вас.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...