绑定字典<字符串,int> to

本文关键字:int to 字符串 字典 绑定 | 更新日期: 2023-09-27 17:56:13

这是我的枚举

public enum Works
{
    [Description("Admin")]
    Admin,
    [Description("Chưa Set")]
    UnSetted,
    [Description("Vào - Ra")]
    InOut,
    [Description("Ra - Vào")]
    OutIn
}

这是我的观点模型

 public class DivisionViewModel : ViewModel<IDivisionView>
{
    private IEnumerable<Account> accounts;
    private ICommand confirmCommand;
    private Dictionary<string, int> works;
....
}

我转换枚举以获取字典并获取这样的帐户

this.divisionViewModel.Accounts = Root.Accounts;
this.divisionViewModel.Works = Enum.GetValues(typeof(Works))
                                   .Cast<Works>()
                                   .ToDictionary(t => Tools.GetEnumDescription((Works)t), t => (int)t);

这是我的 WPF 数据网格

<DataGrid ItemsSource="{Binding Accounts}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <DataGrid.Columns>
                <DataGridTextColumn
                    Binding="{Binding FullName, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, NotifyOnValidationError=True}" 
                                Header="Tên nhân viên" Width="*" ElementStyle="{StaticResource TextCellElementStyle}"
                                EditingElementStyle="{StaticResource TextCellEditingStyle}"/>
                <DataGridComboBoxColumn></DataGridComboBoxColumn>
            </DataGrid.Columns>
        </DataGrid>

如何将this.divisionViewModel.Works绑定到DataGridComboBoxColumn?p/s:我希望我的用户直接在数据网格上更改工作。我已经搜索了SO。但是似乎没有人谈论将Dictionary绑定到DataGridComboBoxColumn。

绑定字典<字符串,int> to

这是空的原因是:

<DataGridComboBoxColumn ItemsSource="{Binding Works.Keys}">

这是因为ComboBox将当前Account绑定为 ViewModel。您需要绑定到DataGrid的视图模型,这就是RelativeSource派上用场的地方:

<DataGridComboBoxColumn  ItemsSource="{Binding Works.Keys, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}">

注意:在 Visual Studio 中检查"输出"窗口,你将看到"绑定"错误,告知你在Account中找不到名为 Work 的属性