我的问题是DataGrid中ComboBox的ItemsSource没有绑定。我的用户控件:
<UserControl x:Class="MyClass"
x:Name="Root"
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"
xmlns:cal="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro"
mc:Ignorable="d"
d:DesignHeight="360" d:DesignWidth="757">
数据网格:
<DataGrid x:Name="Article"
AutoGenerateColumns="False"
SelectionUnit="FullRow"
SelectionMode="Single"
CanUserAddRows="False"
CanUserDeleteRows="True"
Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4"
Margin="5">
<DataGrid.Columns>
<DataGridTemplateColumn Width="*"
Header="Article">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding FilteredArticle, ElementName=Root}" IsEditable="True"
cal:Message.Attach="[Event KeyUp] = [Action FindArticlel($source)]" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
如果我不说 ElementName=Root,他会尝试在 Article 类中绑定 FilteredArticle。如果我说 ElementName=Root,他在运行时会说以下内容:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=Root'. BindingExpression:Path=FilteredArticle; DataItem=null; target element is 'ComboBox' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
FilteredArticle是我的ViewModel中的可绑定集合。所有其他绑定都正常工作。这是怎么回事?使用Caliburn.Micro的最新稳定版本。
通过ElementName
绑定到视图通常是一种不好的做法。主要是因为创建视图实例的人可以为其提供不同的x:Name
,这会破坏您的内部绑定。
此外,FilteredArticle
属性不是视图的属性,而是视图模型的属性,视图模型是视图的数据上下文。
在这些方案中使用相对源进行绑定
ItemsSource="{Binding DataContext.FilteredArticle,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}}"
您可以使用更具体的表示法(尽管在 99% 的情况下没有必要)
ItemsSource="{Binding DataContext.FilteredArticle,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:MyClass}}}"
其中local
是 MyClass
命名空间的xmlns