我在xaml文件中有几个项目要绑定到不同的对象。我用两个按钮显示了一个例子:
<Button Content="Edit Operators"
Command="{Binding ElementName=treeRevisions,
Path=SelectedItem.WorkOrderRev.Operators.EditCommand}" CommandParameter="" />
<Button Content="Edit MyData"
Command="{Binding ElementName=treeRevisions,
Path=SelectedItem.WorkOrderRev.MyData.EditCommand}" CommandParameter="" />
如您所见,两个按钮的文本“Binding ElementName = treeRevisions,Path = SelectedItem.WorkOrderRev”是相同的。它工作,我可以像这样使用它,但我也有很多其他控件。有什么方法可以缩短这个,只需附加“。Operators.EditCommand”等?我到处寻找解决方案,但我没有找到任何东西。
答案 0 :(得分:0)
有几种方法可以做到这一点。我会给你一个非常棘手的帖子。 警告这对于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>
结果将是这样的:
已编辑:相反为True,您可以放置自定义字符串,例如“.Operators.EditCommand”,但您需要更改逻辑。
玩得开心。
答案 1 :(得分:0)
我测试了一些不同的解决方案,发现了一个非常简单 我在周围的网格上设置DataContext,如下所示:
<Grid DataContext="{Binding ElementName=treeRevisions, Path=SelectedItem.WorkOrderRev.PrintData}">
然后我可以使用这样的缩写:
<TextBox Height="23" HorizontalAlignment="Left" Margin="103,63,0,0" Name="txtDescription" VerticalAlignment="Top" Width="120"
IsEnabled="{Binding Path=UnLocked, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
IsReadOnly="{Binding Path=Locked, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
Text="{Binding Path=TableData.Rows[0][description], UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
/>
其中Locked,UnLocked和TableData是SelectedItem.WorkOrderRev.PrintData的属性。