简体   繁体   English

WPF-ConverterParameter中的动态值

[英]WPF - Dynamic value in ConverterParameter

Got a situation where checkboxes in a UI need to be bound to a numeric parameter - effectively, certain values make the checkbox "true", otherwise it's "false". 出现了UI中的复选框需要绑定到数字参数的情况-实际上,某些值使复选框为“ true”,否则为“ false”。

Easiest way to do this seemed to be to use a converter: 最简单的方法似乎是使用转换器:

[ValueConversion(typeof(int), typeof(bool?))]
public class TypeToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(bool?))
            throw new InvalidOperationException("The target must be a bool");

        if( (value < 3)
        {
            return true;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplmentedExpection();
    }
}

And then in the XAML: 然后在XAML中:

<CheckBox IsChecked="{Binding Path=Type.TypeID, Converter={StaticResource TypeConverter}}" />

Which works like a charm when using Convert, but fails utterly when using ConvertBack because it needs to know what the numeric value was (it depends on other UI elements) before it can know what number to return - effectively it needs access to the bound object. 在使用Convert时,它的工作方式像一个超级按钮,但是在使用ConvertBack时,它会完全失败,因为它需要先知道数值(取决于其他UI元素),然后才能知道要返回的数字-有效地,它需要访问绑定的对象。

I assumed I could do this with a ConverterParameter, but from the looks of things you can't bind a value to this property. 我以为我可以使用ConverterParameter做到这一点,但是从外观上看,您不能将值绑定到此属性。

Is there a way out of this mess? 有没有办法摆脱这种混乱?

EDIT: I have solved this by messing around with the original bindings, and got away with it because on uncheck all I want to do is delete the item anyway. 编辑:我已经解决了这个问题,通过弄乱原始绑定,并摆脱了它,因为取消选中我想做的就是删除该项目。 But I'm going to leave this in place since it seems a valid issue and I'm curious about possible solutions. 但是我将保留此位置,因为这似乎是一个有效的问题,并且我对可能的解决方案感到好奇。

Why don't you just bind to something and do the work in what you are binding, for example a viewmodel? 您为什么不只绑定到某个东西,然后在绑定的内容(例如,视图模型)中进行工作? It probably will be cleaner and faster. 它可能会变得越来越干净。

Converters are nice in theory, but after building many large WPF projects, I almost never use them for reasons like above. 转换器在理论上很好,但是在构建了许多大型WPF项目之后,出于上述原因,我几乎再也没有使用它们。 Sure, you can get it to do what you want, but what's the point? 当然,您可以让它做您想做的事,但是有什么意义呢? You have much less control of how and when these conversions happen. 您几乎没有控制如何以及何时进行这些转换。

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

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