【发布时间】:2019-09-05 19:00:14
【问题描述】:
我在 WPF 应用程序中有 ListView 和 GridView。我使用下面的代码在 xaml 中添加了几个 Gridviewcolumn,其中包含 celltemplate 和 DataTemplate。
<GridView x:Name="DvGridView">
<GridViewColumn Header="Device Name" Width="200">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DeviceName}">
<TextBlock.Background>
<SolidColorBrush Color="{Binding DeviceColor}"/>
</TextBlock.Background>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
我想根据用户选择在后面的代码中添加额外的 Gridview 列。我试过下面的代码
GridViewColumn nameColumn = new GridViewColumn();
nameColumn.Header = columnInfo;
nameColumn.Width = 120;
var text = new FrameworkElementFactory(typeof(TextBlock));
text.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Center);
Binding binding = new Binding("DeviceColor");
binding.Source = PmcDataInfoCollection;
SolidColorBrush brush = new SolidColorBrush();
BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);
text.SetBinding(TextBlock.TextProperty, new Binding(col));
text.SetBinding(TextBlock.BackgroundProperty, binding);
DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = text;
nameColumn.CellTemplate = dataTemplate;
DvGridView.Columns.Add(nameColumn);
“DeviceColor”的TextBlock.BackgroundProperty 绑定无法正常工作。它始终以白色显示。请告诉我如何解决此问题。
【问题讨论】:
-
什么是
PmcDataInfoCollection?为什么会有SolidColorBrush brush?它显然没有在任何地方使用。 -
PmcDataInfoCollection 是具有 DeviceColor 属性的 DataContext。刷子用于装订。 BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);
-
BindingOperations.SetBinding显然是在brush上设置了一个Binding,但是brush以后用什么?在这里的代码中,它是完全多余的,应该被删除。 -
是的,但我们需要将该属性绑定到 TextBlock.BackgroundProperty。正确吗?
-
请看答案。请注意,当 DataContext 已经包含 PmcDataInfoCollection 对象时,您不需要设置 Binding 的 Source 属性。
标签: c# .net wpf data-binding