Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing ValueConverter to variable

I am having a ValueConverter used for binding 'To' Value in a StoryBoard animation, similar to the answer - WPF animation: binding to the “To” attribute of storyboard animation.

The problem is I am repeating the below piece of code for MultiBinding ValueConverter in couple of places.

    <MultiBinding Converter="{StaticResource multiplyConverter}">
       <Binding Path="ActualHeight" ElementName="ExpanderContent"/>
       <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
    </MultiBinding>

I want to remove this duplicate code by storing the result of the ValueConverter to a resource variable so I can bind this local Variable directly to the story board.

<system:Double x:Key="CalculatedWidth">
    <MultiBinding Converter="{StaticResource multiplyConverter}">
        <Binding Path="ActualHeight" ElementName="ExpanderContent"/>
        <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
    </MultiBinding>
</system:Double >

I am getting the following error:

The type 'Double' does not support direct content.

Cannot add content to an object of type "Double".

I feel this is a common problem but not able to find a solution to remove this redundancy.

Update

Thanks Rohit, your answer solved the problem. But I have one more related issue, So updating the question. This variable CalculatedWidth works fine in normal case, but when it is used in RenderTransform it doesn't pick up the value. i.e. If I use the normal way to use Converter it works but it doesn't pick up the variable.

<StackPanel.RenderTransform>
    <TranslateTransform x:Name="SliderTransform">
        <TranslateTransform.X>
            <Binding Converter="{StaticResource PanelConverter}" ElementName="SliderPanel" Path="ActualWidth" /> // Works
            <Binding Path="Width" Source="{StaticResource CalculatedWidth}"/> // Doesn't Work
        </TranslateTransform.X>
    </TranslateTransform>
</StackPanel.RenderTransform>

I have kept the variable as part of the local resource. Does this mean the variable doesn't get created when Render transform is called?

like image 918
Carbine Avatar asked Jan 03 '14 07:01

Carbine


1 Answers

As the error suggest you can't bind with Double. Binding can be done with only Dependency properties.

Instead use FrameworkElement in resource and bind its Width(DP) like this:

<FrameworkElement x:Key="CalculatedWidth">
    <FrameworkElement.Width>
        <MultiBinding Converter="{StaticResource multiplyConverter}">
            <Binding Path="ActualHeight" ElementName="ExpanderContent"/>
            <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
        </MultiBinding>
     </FrameworkElement.Width>
</FrameworkElement>

and you can bind with this resource like in this sample:

<TextBlock Width="{Binding Width, Source={StaticResource CalculatedWidth}}"/>
like image 137
Rohit Vats Avatar answered Oct 10 '22 14:10

Rohit Vats