Ser*_*gey 5 c# wpf xaml binding datagrid
我想将第三列绑定到CollectionBindingTwo
Window 的 DataContext 内的属性,而不是来自CollectionBindingOne
.
通过在 WPF 中定义第二个集合,<DataGrid>
假定本地范围或其他内容,并指向 ItemsSource () 的 Items 中的属性CollectionBindingOne
。
<DataGrid DockPanel.Dock="Top" ItemsSource="{Binding CollectionBindingOne}" AutoGenerateColumns="False">
<DataGridTextColumn Header="One" Binding="{Binding PropOne}"/>
<DataGridTextColumn Header="Two" Binding="{Binding PropTwo}"/>
<DataGridComboBoxColumn Header="Three" ItemsSource="{Binding CollectionBindingTwo}"/>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
例如,这有效,因为ComboBox
不在 a 内<DataGrid>
:
<ComboBox IsEditable="True" ItemsSource="{Binding CollectionBindingTwo}"></ComboBox>
Run Code Online (Sandbox Code Playgroud)
DataGridComboBoxColumn 不是可视化树的一部分,因此通常的RelativeSource/ElementName 绑定格式将不起作用。您可以通过定义这些绑定格式将起作用的ElementStyle 和 EditingStyle来使用解决方法。另一种选择是使用 BindingProxy,我将其用于其他位置,并且在没有其他原因定义 ElementStyle/EditingStyle 时将节省一些 XAML。
这是继承自 Freezable 的 BindingProxy 类。
public class BindingProxy : Freezable
{
#region Overrides of Freezable
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
#endregion
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data.
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data",
typeof(object),
typeof(BindingProxy),
new UIPropertyMetadata(null));
}
Run Code Online (Sandbox Code Playgroud)
现在你的 xaml 看起来像这样:
<DataGrid DockPanel.Dock="Top"
ItemsSource="{Binding CollectionBindingOne}"
AutoGenerateColumns="False">
<DataGrid.Resources>
<helper:BindingProxy x:Key="proxy"
Data="{Binding }" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="One"
Binding="{Binding PropOne}" />
<DataGridTextColumn Header="Two"
Binding="{Binding PropTwo}" />
<DataGridComboBoxColumn Header="Three"
ItemsSource="{Binding Data.CollectionBindingTwo,
Source={StaticResource proxy}}" />
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
不要忘记在 Window/UserControl 顶部声明辅助命名空间导入。
归档时间: |
|
查看次数: |
1765 次 |
最近记录: |