我陷入了一个必须动态创建数据网格列并且必须在 C# 代码中创建列的场景中。对于每个生成的列,我在单独的代码区域中有一个复选框。该复选框确定特定列是隐藏还是可见。该复选框绑定到 GameAttributes.Visible 属性。但是,DataGrid Visibility 属性是不同的类型。我尝试使用 BooleanToVisibilityConverter,但仍然收到编译错误(如我所想)。有没有任何有效的解决方法来解决这个问题?
我遇到的错误:
Cannot implicitly convert type 'bool' to 'System.Windows.Visibility'
编辑:编译器错误已解决,但绑定似乎不适用于可见性。
XAML:
<DataGrid ItemsSource="{Binding}"
DockPanel.Dock="Top"
AutoGenerateColumns="False"
HorizontalAlignment="Stretch"
Name="GameDataGrid"
VerticalAlignment="Stretch"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserResizeRows="False"
IsReadOnly="True"
>
看法:
GameAttributes.Add(new GameInfoAttributeViewModel() { Visible = true, Description = "Name", BindingName = "Name" });
GameAttributes.Add(new GameInfoAttributeViewModel() { Visible = false, Description = "Description", BindingName = "Description" });
GameAttributes.Add(new GameInfoAttributeViewModel() { Visible = false, Description = "Game Exists", BindingName = "GameExists" });
foreach (GameInfoAttributeViewModel attribute in GameAttributes)
{
DataGridTextColumn column = new DataGridTextColumn
{
Header = attribute.Description,
Binding = new Binding(attribute.BindingName),
};
Binding visibilityBinding = new Binding();
visibilityBinding.Path = new PropertyPath("Visible");
visibilityBinding.Source = attribute;
visibilityBinding.Converter = new BooleanToVisibilityConverter();
BindingOperations.SetBinding(column, VisibilityProperty, visibilityBinding);
GameDataGrid.Columns.Add(column);
}
视图模型:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
namespace DonsHyperspinListGenerator
{
class GameInfoAttribute
{
public string Description { get; set; }
public bool Visible { get; set; }
public string BindingName { get; set; }
}
//todo: move to separate class
class GameInfoAttributeViewModel : INotifyPropertyChanged
{
private GameInfoAttribute mGameInfo = new GameInfoAttribute();
public string Description
{
get { return mGameInfo.Description; }
set
{
if (mGameInfo.Description != value)
{
mGameInfo.Description = value;
InvokePropertyChanged("Description");
}
}
}
public bool Visible
{
get { return mGameInfo.Visible; }
set
{
if (mGameInfo.Visible != value)
{
mGameInfo.Visible = value;
InvokePropertyChanged("Visible");
}
}
}
public string BindingName
{
get { return mGameInfo.BindingName; }
set
{
if (mGameInfo.BindingName != value)
{
mGameInfo.BindingName = value;
InvokePropertyChanged("BindingName");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void InvokePropertyChanged(string propertyName)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null) changed(this, e);
}
}
}