如何在WPF中获取按钮的当前启用/禁用状态'Convert'方法

本文关键字:状态 启用 方法 Convert WPF 获取 按钮 | 更新日期: 2023-09-27 18:12:15

我的程序有这种多重绑定

<MultiBinding Converter="{StaticResource myConverter}" Mode="OneWay">
<Binding Path="SelectedItems.Count"/>
<Binding Path="EffectiveStyleContext.Selection"/>
</MultiBinding>

是否有在Convert方法中获得当前启用禁用状态

class myConverter: IMultiValueConverter
{
    public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //I need to get current status here
    }
}

如何在WPF中获取按钮的当前启用/禁用状态'Convert'方法

您必须将控制本身传递给ValueConverter

修改后的Xaml将是

<MultiBinding Converter="{StaticResource myConverter}" Mode="OneWay">
    <Binding RelativeSource="{RelativeSource Self}"/>
    <Binding Path="SelectedItems.Count"/>
    <Binding Path="EffectiveStyleContext.Selection"/>
</MultiBinding>

现在在你的转换器代码中,你将能够访问控制。

public class MyConverter : IMultiValueConverter
{  
    public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var control = values[0] as FrameworkElement;
        var value1 = values[1] as int;
        // write your logic here.          
    }
    public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        return throw new System.NotImplementedException();;
    }
}

您也可以直接绑定到属性本身:

<Binding Path="IsEnabled" RelativeSource="{RelativeSource Self}" />

我认为这是可取的,因为当启用状态改变时,MultiBinding不会得到更新。