我想创建一个像这样的链绑定:我有一个用户控件,在具有类似依赖属性的窗口内具有依赖属性。我想将用户控件的依赖属性绑定到窗口的依赖属性。
我创建了一个示例项目来演示我的问题:
用户控件1 XAML:
<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" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Label Content="{Binding Caption}"/>
</Grid>
</UserControl>
用户控件1 C#:
public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(UserControl1));
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
public UserControl1()
{
InitializeComponent();
}
}
主窗口 XAML:
<Window xmlns:WpfApplication1="clr-namespace:WpfApplication1" x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Content="{Binding Caption, Mode=OneWay}"/>
<WpfApplication1:UserControl1 x:Name="uc" Caption="{Binding Caption, Mode=OneWay}" Grid.Row="1"/>
</Grid>
</Window>
主窗口 C#:
public partial class MainWindow : Window
{
public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(MainWindow));
public string Caption
{
get { return (string)GetValue(CaptionProperty); }
set { SetValue(CaptionProperty, value); }
}
public MainWindow()
{
InitializeComponent();
(new Thread(() => { Thread.Sleep(2000); Dispatcher.Invoke(() => { uc.Caption = "YYY"; Caption = "XXX"; }); })).Start();
}
}
问题是,当我将 Caption 设置为(窗口的)“XXX”时,我希望它也通知用户控件并更新其 Caption,但事实并非如此。我想避免附加依赖属性并尽可能避免代码隐藏。有任何想法吗?
感谢您的任何努力。