【发布时间】:2019-02-17 08:32:22
【问题描述】:
我有一个用户控件
我的绑定开始工作,然后在我与控件交互时停止。
<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MyUserControl}}}">
<StackPanel Orientation="Horizontal">
<TextBox Width="100" Background="Cyan"
Text="{Binding Path=DP_in_UserControl,
FallbackValue='Fallback',
TargetNullValue='TargetNull',
UpdateSourceTrigger=PropertyChanged}"/>
<Label Width="100" Background="Magenta"
Content="{Binding Path=DP_in_UserControl,
FallbackValue='Fallback',
TargetNullValue='TargetNull'}"/>
</StackPanel>
</Grid>
public partial class MyUserControl : UserControl
{
public string DP_in_UserControl
{
get { return (string)GetValue(DP_in_UserControlProperty); }
set { SetValue(DP_in_UserControlProperty, value); }
}
public static readonly DependencyProperty DP_in_UserControlProperty =
DependencyProperty.Register("DP_in_UserControl", typeof(string),
typeof(MyUserControl), new PropertyMetadata("UC Default"));
public MyUserControl()
{
InitializeComponent();
}
}
我有一个主窗口:
<StackPanel Margin="25">
<local:MyUserControl VerticalAlignment="Top"
DP_in_UserControl="{Binding DP_in_MainWindow}"/>
<Label Background="Yellow"
Content="{Binding DP_in_MainWindow,
FallbackValue='Fallback',
TargetNullValue='TargetNull'}"/>
<Button Content="Change DP__in__MainWindow"
Click="Button_Click"/>
</StackPanel>
public partial class MainWindow : Window
{
public string DP_in_MainWindow
{
get { return (string)GetValue(DP_in_MainWindowProperty); }
set { SetValue(DP_in_MainWindowProperty, value); }
}
public static readonly DependencyProperty DP_in_MainWindowProperty =
DependencyProperty.Register("DP_in_MainWindow", typeof(string),
typeof(MainWindow), new PropertyMetadata("MW Default"));
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e) =>
DP_in_MainWindow = "Changed";
}
生成的窗口开始为:
如果我在 UserControl(青色)上的 TextBox 中键入,则只有 UserControl 的标签(洋红色)会更新:
如果我然后单击更改 DP_in_MainWindow 的按钮,则只有 MainWindow(黄色)中定义的标签会更新。
但是如果我重新启动它并首先单击按钮,所有三个都会正确更新:
然后再次输入会破坏 Bindings 并且只更新控件的标签:
这里发生了什么以及如何使绑定以 XAML 方式保持其绑定性。我知道我可以在 C# 中将它一起破解,这是我看到的大部分答案,但必须有一个简单的“正确”方法来做到这一点。
我已经尝试过各种 ControlTemplates 组合和按名称替换的绑定......只是没有找到正确的组合。
【问题讨论】:
-
您是否尝试过将
Mode指定为TwoWay? -
@dhilmathy 我做过,但我不记得当时我有什么其他混乱。我现在将它们全部设置为 TwoWay 并报告。
-
@dhilmathy 我知道我已经尝试过了,但这就是问题所在。有问题的绑定是
<local:MyUserControl DP_in_UserControl="{Binding DP_in_MainWindow}"/>把它作为答案,我会捣碎接受按钮。 -
有人会无耻地盗用我漂亮的博客示例,我相信人们会阅读它。
标签: c# xaml data-binding dependency-properties