[英]Refactoring creation of a binding from code-behind based to XAML based
Today I'm using a constructor to receive an array and then bind it to the element. 今天,我正在使用构造函数来接收数组,然后将其绑定到元素。
C# C#
public MyDialog(Stuff stuff, IEnumerable<Thing> things)
{
InitializeComponent();
DataContext = stuff;
MyComboBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding { Source = things });
ShowDialog();
}
XAML XAML
<ComboBox x:Name="MyComboBox"
DisplayMemberPath="Canonic"
Style="{StaticResource DefaultComboBoxStyle}" />
I'd like to refactor it into purely XAML based approach and I've approached it in the following way. 我想将其重构为纯粹基于XAML的方法,并且已通过以下方式进行了处理。 However, I get no values in my combo box now and I'm very unsure how to trouble-shoot it.
但是,现在我的组合框中没有任何值,而且我不确定如何解决它。
<ComboBox x:Name="MyComboBox"
ItemsSource="{Binding
RelativeSource={
RelativeSource FindAncestor,
AncestorType={x:Type Window}},
Path=DataContext.TheActualThings}"
DisplayMemberPath="Canonic"
Style="{StaticResource DefaultComboBoxStyle}" />-->
Of course, the class Things contains a number of fields, one of which is called Canonic and contains a string to render as the option description. 当然, Things类包含许多字段,其中一个字段称为Canonic,并包含要呈现为选项描述的字符串。 The control creating the dialog is of type ProgramWindow deriving from Window .
创建对话框的控件是从Window派生的ProgramWindow类型。
Please note that there's a similar question (as it may appear) but the difference is that in the other, I had syntax issue and once that's resolved, there's the actual technical problem described here. 请注意,有一个类似的问题(可能会出现),但区别在于另一个问题是语法问题,一旦解决,这里将描述实际的技术问题。 (I'm not giving a link to the other question because I prefer not to affect the view count on it.)
(我没有提供其他问题的链接,因为我不希望影响该视图的计数。)
public partial class ProgramWindow : Window
{
public ProgramWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
private void DataGridRow_OnDoubleClick(Object sender, MouseButtonEventArgs eventArgs)
{
MyDialog dialog = new MyDialog(
(sender as DataGridRow).Item as Stuff,
(DataContext as ViewModel).TheActualThings);
if (dialog.DialogResult ?? false) ...
else ...
}
}
The problem is that you are trying to access the DataContext
of another Window
using a RelativeSource binding. 问题是您试图使用RelativeSource绑定访问另一个
Window
的DataContext
。 The RelativeSource
binding can only access elements within the same visual tree and the other Window
cannot be accessed this way. RelativeSource
绑定只能访问同一可视树中的元素,而其他Window
不能以这种方式访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.