0

我有两个枚举:

public enum MyEnumA
{
    OptionA1 = 1,
    OptionA2 = 2,
    OptionA3 = 3,
}

public enum MyEnumB
{
    OptionB1 = 1,
    OptionB2 = 2,
    OptionB3 = 3,
}

和一个包含两个枚举的类

public class AB
{
    public MyEnumA A { get; set; }
    public MyEnumB B { get; set; }
}

我想要两个枚举的复选框矩阵。数据从列表中读取并保存到列表中。此列表是实际的联结表。暂时我手动填写了清单:

    private List<AB> ABList = new List<AB>();

    ABList.Add(new AB { A = MyEnumA.OptionA2, B = MyEnumB.OptionB1 });
    ABList.Add(new AB { A = MyEnumA.OptionA3, B = MyEnumB.OptionB3 });

矩阵现在应该如下所示:

            OptionA1 OptionA2 OptionA3
OptionB1                 X
OptionB2
OptionB3                          X

我找到了一个 WinForm 解决方案,其中一切都在代码隐藏中完成: http: //social.msdn.microsoft.com/Forums/eu/winformsdatacontrols/thread/33fae605-902a-40e3-9bbb-60b77fc33b9b但不能用数据绑定在 xaml 中完成?

4

2 回答 2

1

感谢您的解决方案,Grafix。这是很不错的。我认为将它放在转换器中会更整洁,所以我这样做了:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var abList = value as List<AB>;

        if (abList == null)
            return null;

        var retVal = Enum.GetValues(typeof (MyEnumB)).Cast<MyEnumB>().Select(
                b =>
                new ABViewModel()
                    {
                        Name = b,
                        OptionA1 = abList.Any(ab => ab.B == b && ab.A == MyEnumA.OptionA1),
                        OptionA2 = abList.Any(ab => ab.B == b && ab.A == MyEnumA.OptionA2),
                        OptionA3 = abList.Any(ab => ab.B == b && ab.A == MyEnumA.OptionA3)
                    }).ToList();
        return retVal;
    }

和数据网格:

    <DataGrid Height="215" HorizontalAlignment="Left" Margin="91,12,0,0" Name="dataGrid1" 
            VerticalAlignment="Top" Width="299" 
            ItemsSource="{Binding ABList, Converter={StaticResource listToDataTableConverter}}"
            d:DataContext="{d:DesignData }" />

我像这样设置DataContext:

    public MainWindow()
    {
        InitializeComponent();

        ABList.Add(new AB { A = MyEnumA.OptionA2, B = MyEnumB.OptionB1 });
        ABList.Add(new AB { A = MyEnumA.OptionA3, B = MyEnumB.OptionB3 });

        DataContext = this;
    }
于 2012-11-09T12:44:12.333 回答
1

如果您想将 WPF DataGrid 与数据绑定一起使用,我认为除了转换数据之外别无他法。

        public MainWindow()
    {
        InitializeComponent();

        DataContext = Enum.GetValues(typeof(MyEnumB)).Cast<MyEnumB>().Select(b => new ABViewModel() { Name = b.ToString(), A1 = ABList.Any(ab => ab.B == b && ab.A == MyEnumA.OptionA1), A2 = ABList.Any(ab => ab.B == b && ab.A == MyEnumA.OptionA2), A3 = ABList.Any(ab => ab.B == b && ab.A == MyEnumA.OptionA3) }).ToList();
    }


public class ABViewModel
{
    public string Name { get; set; }
    public bool A1 { get; set; }
    public bool A2 { get; set; }
    public bool A3 { get; set; }
}

Xaml 现在很简单:

<DataGrid ItemsSource="{Binding}" IsReadOnly="True"/>
于 2012-11-08T07:35:56.010 回答