有几种方法可以做到这一点。我会给你一个非常棘手的。警告这对于 wpf pro 来说是一个疯狂的答案,但它确实有效。哈哈哈……
public MainWindow()
{
InitializeComponent();
this.DataContext = new { D = "Hello" };
}
public static bool GetDoMyBinding(DependencyObject obj)
{
return (bool)obj.GetValue(DoMyBindingProperty);
}
public static void SetDoMyBinding(DependencyObject obj, bool value)
{
obj.SetValue(DoMyBindingProperty, value);
}
// Using a DependencyProperty as the backing store for DoMyBinding. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DoMyBindingProperty =
DependencyProperty.RegisterAttached("DoMyBinding", typeof(bool), typeof(MainWindow), new PropertyMetadata(false, new PropertyChangedCallback(OnDoMyBindingChanged)));
private static void OnDoMyBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Binding binding = new Binding("D");
binding.Mode = BindingMode.OneWay;
if (d is Button)
{
Button b = d as Button;
b.SetBinding(Button.ContentProperty, binding);
}
if (d is TextBlock)
{
TextBlock tb = d as TextBlock;
tb.SetBinding(TextBlock.TextProperty, binding);
}
}
您的 XAML 将如下所示:
<Window x:Class="BindingTest.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"
xmlns:local="clr-namespace:BindingTest">
<StackPanel>
<Button local:MainWindow.DoMyBinding="True"/>
<Button local:MainWindow.DoMyBinding="True"/>
<TextBlock local:MainWindow.DoMyBinding="True" />
</StackPanel>
</Window>
结果将是这样的:
已编辑:相反,您可以放置自定义字符串,例如“.Operators.EditCommand”,但您需要更改逻辑。
玩得开心。