将字典<string,int =“”>绑定到</string,>

时间:2014-04-02 10:42:43

标签: c# wpf binding

这是我的Enum

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

这是我的ViewModel

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

我将enum转换为获取字典并获得此类帐户

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

<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:我希望我的用户直接在DataGrid上更改Work。我已经开始了。但似乎没有人谈论将Dictionary绑定到DataGridComboBoxColumn。

1 个答案:

答案 0 :(得分:0)

这是空的原因:

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

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

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

注意:检查Visual Studio中的输出窗口,您会看到绑定错误,告诉您他们无法在Work <中找到名为Account的属性/ p>