简体   繁体   中英

Can binding be used in XAML within a Style?

I wrote a sample to see if binding could be used within a Style in a blank Windows Store app - it compiled but did not work exactly as I'd hoped. I'm relatively new to XAML and binding so may have missed something.

In the sample below there are two rectangles, both bound to the slider control and both should change at the same time as the slider is moved, but it seems that only the first one changes; the first one is bound directly, the second is bound via a style .

Is binding in a Style supposed to be possible in a Win Store app? (My aim is to have a slider that changes the settings on a large number of elements at once, it seemed like this would be a better approach than copy/pasting bindings to all of them)

<Grid Background="#FF87873D">

    <StackPanel>
        <StackPanel.Resources>
            <Style x:Key="myTestRectangleStyle" TargetType="Rectangle">
                <Setter Property="Fill" Value="DarkBlue" />
                <Setter Property="Margin" Value="10,10" />
                <Setter Property="Height" Value="30" />
                <Setter Property="Width" Value="{Binding ElementName=slider1, Path=Value}" />
            </Style>
        </StackPanel.Resources>

        <Rectangle Width="{Binding ElementName=slider1, Path=Value}" Fill="Black" Margin="10,10" Height="30"/>

        <Rectangle Style="{StaticResource myTestRectangleStyle}"/>

        <Slider Name="slider1" Minimum="20" Maximum="200" Margin="20,0"/>
    </StackPanel>
</Grid>

Answering my own question...it seems this isn't possible on a Windows Store App.

I had a clarification from a user on a MSDN forum that

[Bindings] are not supported on Style setters in Windows Store Apps like they are in WPF, ie you cannot bind to the Value property of the Slider in the Style

So the workaround is just to set the binding directly outside of the Style (a long winded option if you have a lot of elements to bind unfortunately)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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