質問

I have an interface with multiple buttons. I'd like to enable or disable these buttons according to a 'complex' condition. I declared this MultiBinding as an application resource in order to avoid code repetition:

<MultiBinding x:Key="MyMultiBinding" Converter="{StaticResource ResourceKey=MyConverter}">
    <Binding Path="IsConnected" />
    <Binding Path="IsOpened" />
</MultiBinding>

Here is how I declare my button:

<Button Name="MyButton" Content="Click me!" IsEnabled="{StaticResource ResourceKey=MyMultiBinding}" />

At runtime, I get the following error: "Set property IsEnabled threw an exception... MultiBinding is not a valid value for property IsEnabled".

I can't figure why this is not working. Could you please point me to the right way to do this? Thank you.

役に立ちましたか?

解決

You can't set the boolean IsEnabled property to a value of type MultiBinding. That is what is happening.

As @Viv pointed out, you could declare a Style to do the heavy lifting:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="IsEnabled">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
                <Binding Path="IsConnected" />
                <Binding Path="IsOpened" />
            </MultiBinding>
        </Setter.Value> 
    </Setter>
</Style>

<Button Name="MyButton" Content="Click me!" Style="{StaticResource ButtonStyle}" />

This works well if the Button DataContext has those properties. It works especially well if they each have a different DataContext they are bound to, enabling them for different reasons.

If they are all bound to the same DataContext, or the properties are on a different object, you could use the Freezable Trick to provide a value that your buttons would bind to:

<BindingProxy x:Key="isEnabled">
    <BindingProxy.Data>
        <MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
            <Binding Path="IsConnected" />
            <Binding Path="IsOpened" />
        </MultiBinding>
    </BindingProxy.Data>
</BindingProxy>

<Button Name="MyButton" Content="Click me!" IsEnabled="{Binding Data, Source={StaticResource isEnabled}}" />

他のヒント

I don't know if this is the best solution, but wrapping the MultiBinding into a style, as Viv said, did the trick. Here is the code of the Style :

<Style x:Key="MyStyle" TargetType="Button">
    <Style.Setters>
        <Setter Property="IsEnabled">
            <Setter.Value>
                <MultiBinding Converter="{StaticResource ResourceKey=MyConverter}">
                    <Binding Path="IsConnected" />
                    <Binding Path="IsDataAccessOpened" />
                </MultiBinding>
            </Setter.Value>
        </Setter>
    </Style.Setters>
</Style>

And the code of the button :

<Button Name="MyButton" Content="Click me!" Style={StaticResource ResourceKey=MyStyle} />
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top