putting multibinding on a single line in xaml

一笑奈何 提交于 2019-12-03 05:47:51

A better (and simpler) approach would be to define a style as a resource which you can easily apply to any TextBox:

<Window.Resources>
    <c:MyLogicConverter x:Key="LogicConverter" />

    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}" x:Key="MultiBound">
        <Setter Property="IsEnabled">
            <Setter.Value>
                <MultiBinding Converter="{StaticResource LogicConverter}">
                    <Binding ElementName="switch" Path="IsEnabled" />
                    <Binding ElementName="switch" Path="IsChecked" />
                </MultiBinding>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<StackPanel Orientation="Horizontal">
    <CheckBox Name="switch" />
    <TextBox Name="textBox2" Text="Test" Style="{StaticResource MultiBound}" />
</StackPanel>

This can be done with a custom markup extension:

public class MultiBinding : System.Windows.Data.MultiBinding
{
    public MultiBinding (BindingBase b1, BindingBase b2)
    {
        Bindings.Add(b1);
        Bindings.Add(b2);
    }

    public MultiBinding (BindingBase b1, BindingBase b2, BindingBase b3)
    {
        Bindings.Add(b1);
        Bindings.Add(b2);
        Bindings.Add(b3);
    }

    // Add more constructors if you need.
}

Usage:

<TextBox IsEnabled="{local:MultiBinding
    {Binding IsEnabled, ElementName=prog0_used},
    {Binding IsChecked, ElementName=prog0_used},
    Converter={StaticResource LogicConverter}}">

For MultiBinding there is no shorthand string. You need to use the expanded element syntax.

I tried using Discord's answer, but it didn't work right out of the box. To make it work I added a new constructor:

public class MultiBinding : System.Windows.Data.MultiBinding
{
    public MultiBinding(BindingBase b1, BindingBase b2, object converter)
    {
        Bindings.Add(b1);
        Bindings.Add(b2);
        Converter = converter as IMultiValueConverter;
    }
}

Usage will then be like this:

    <TextBox IsEnabled="{local:MultiBinding {Binding IsEnabled, ElementName=prog0_used}, 
{Binding IsChecked, ElementName=prog0_used}, 
{StaticResource LogicConverter}}">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!