简体   繁体   English

WPF DataGrid组合框更改选择问题

[英]WPF DataGrid combobox change selection issue

I have a DataGrid with one column that has a ComboBox in it: 我有一个数据网格,其中有一个包含ComboBox的列:

    DataGridTemplateColumn colDataType = new DataGridTemplateColumn();
    colDataType.Header = "Type";
    var cboFactoryDT = new FrameworkElementFactory(typeof(ComboBox));
    cboFactoryDT.SetValue(ComboBox.ItemsSourceProperty, Enum.GetValues(typeof(BuilderDataTypes)).Cast<BuilderDataTypes>());
    b = new Binding("Value[1]");
    b.Converter = new ObjectToDataTypeConverter();
    b.UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
    b.Mode = BindingMode.TwoWay;
    cboFactoryDT.SetBinding(ComboBox.SelectedIndexProperty, b);
    cboFactoryDT.SetValue(ComboBox.IsSynchronizedWithCurrentItemProperty, true);
    DataTemplate dtDT = new DataTemplate { VisualTree = cboFactoryDT };
    colDataType.CellTemplate = dtDT;

And my Converter class is: 我的Converter类是:

public class ObjectToDataTypeConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        try
        {
            return int.Parse(value.ToString());
        }
        catch { return 0; }
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        try
        {
            return value;
        }
        catch { return 0; }
    }
}

Now, the problem is when I change the selection in one of the rows, all the comboboxes in all the rows are changed to the same selection as well. 现在,问题是当我更改某一行中的选择时,所有行中的所有组合框也都更改为相同的选择。

What could be the problem? 可能是什么问题呢?

Seeing exception handling like yours is a pet-pevee of mine. 看到像您一样的异常处理是我的宠儿。 Your code has the abiltiy to swallow Fatal Exceptions, wich is a deadly sin of Exception handling. 您的代码有能力吞下致命异常,这是异常处理的致命罪过。 You should read these articles on proper exception handling: 您应该阅读有关适当的异常处理的以下文章:

http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in -净

What wonders me even more, is that you do that faulty handling to Parse. 更令我惊讶的是,您对Parse的处理不正确。 If you do not want the Vexing Exceptions, there is TryParse just for that. 如果您不希望使用Vexing异常,则可以使用TryParse。 The only reason to not use it, is if you somehow are below Framework Version 2.0, where it was introduced. 不使用它的唯一原因是,如果您不知何故在引入它的Framework Version 2.0以下。 I have repalcement code for that case, but with WPF that seems unlikely. 对于这种情况,我有补给代码,但是使用WPF似乎不太可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM