C# 通过转换器绑定SelectedValue与ItemsSource中的任何内容都不匹配

C# 通过转换器绑定SelectedValue与ItemsSource中的任何内容都不匹配,c#,wpf,data-binding,combobox,C#,Wpf,Data Binding,Combobox,我有一个如下所示的组合框,其中SelectedValue绑定到int,ItemsSource绑定到字符串集合: combobox选项按我预期的方式填充,当调用转换器时,它将按预期返回,但它仅在控件首次呈现时被调用-在选择时不会按我预期的方式更改 现在,问题是:当组合框选择被更改时,更改不起作用-永远不会调用setter on值,并且选择丢失。您的绑定看起来正常,因此当选择更改时,应该调用转换器的ConvertBack方法。你查过了吗 ConvertBack方法的返回值实际上返回一个整数,这一点很

我有一个如下所示的组合框,其中SelectedValue绑定到int,ItemsSource绑定到字符串集合:

combobox选项按我预期的方式填充,当调用转换器时,它将按预期返回,但它仅在控件首次呈现时被调用-在选择时不会按我预期的方式更改


现在,问题是:当组合框选择被更改时,更改不起作用-永远不会调用setter on值,并且选择丢失。

您的绑定看起来正常,因此当选择更改时,应该调用转换器的ConvertBack方法。你查过了吗

ConvertBack方法的返回值实际上返回一个整数,这一点很重要。否则,无法正确设置绑定的Value属性

如果您的If声明:

if (helper.StringToIntDictionary.TryGetValue(priority, out priorityInt))
返回false,值永远不会设置为整数,因此永远不会调用value属性的setter。您还将得到一个错误,在调试FormatException时,可以在输出窗口中看到该错误


所以我会从ConvertBack方法开始研究。确保从字符串到int的转换在任何情况下都有效。也许您还应该指定一个默认值,如果TryGetValue方法返回false,则会返回该值,以确保在任何情况下都会返回有效值。

不过,在控件初始启动后不会调用Convert/ConvertBack。我在两者的顶部都有断点,我在启动时按了2次Convert,在启动时按了1次ConvertBack,但之后都没有。如果选择中的每个更改都没有触发Convert/ConvertBack..,我假设与ItemsSource的匹配不可能工作?您的假设是正确的。问题发生得更早。似乎在初始加载控件后绑定被破坏。控件中是否有其他绑定,以及这些绑定在初始加载后是否工作?初始加载后是否正确设置了DataContext?
public class PriorityIntToStringConverter : IValueConverter
{
    private static readonly HelperClass helper = HelperClass.Instance;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is int)
        {
            int priority = (int)value;
            string priorityStr;
            if (helper.IntToStringDictionary.TryGetValue(priority, out priorityStr))
            {
                value = priorityStr;
            }
        }

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string priority = value as string;
        if (priority != null)
        {
            int priorityInt;
            if (helper.StringToIntDictionary.TryGetValue(priority, out priorityInt))
            {
                value = priorityInt;
            }
        }

        return value;
    }
}
if (helper.StringToIntDictionary.TryGetValue(priority, out priorityInt))