djcmm476
djcmm476

Reputation: 1813

Dynamic Bindings in XAML

So I'm trying to alter some XAML code to add in a context menu that will change the number of decimal places of a value. My XAML is a little weak though and I'm getting a bit lost.

The code I have right now is:

<MenuItem Header="{DynamicResource DecimalPlaces}" ItemsSource="{Binding MenuItems}">
    <ExclusiveMenuItem:ExclusiveMenuItem Header="{DynamicResource oneDecimal}" IsCheckable="True" IsChecked="{Binding Path=DecimalPlaces}"/>
    <ExclusiveMenuItem:ExclusiveMenuItem Header="{DynamicResource twoDecimal}" IsCheckable="True" IsChecked="{Binding Path=DecimalPlaces}"/>
</MenuItem>

This will at least make the menu appear, but the problem is the DecimalPlaces handles ints (I've just put oneDecimal and twoDecimal in as placeholders for now) and I want the dynamic resource to be an int, preferably to go from one to ten too.

So my question is: how can I set the dynamic resource to an integer rather than a specific variable and is there a way to dynamically generate this menu (as opposed to writing 10 different entries), maybe based on an array or something?

Sorry if this is a pretty simple question, like I said, my XAML is a bit weak. Any help greatly appreciated.

Upvotes: 0

Views: 142

Answers (1)

TTat
TTat

Reputation: 1496

If I understand your question correctly, I don't think a DynamicResource is what you need. A DynamicResource is a Resource that will get resolved at Runtime. This is usually used for theming.

It's a little hard to understand exactly what you're trying to do, but if you just want the header to display some text, just set it.

<MenuItem Header="{DynamicResource DecimalPlaces}" ItemsSource="{Binding MenuItems}">
    <ExclusiveMenuItem:ExclusiveMenuItem Header="1" IsCheckable="True" IsChecked="{Binding Path=DecimalPlaces}"/>
    <ExclusiveMenuItem:ExclusiveMenuItem Header="2" IsCheckable="True" IsChecked="{Binding Path=DecimalPlaces}"/>
    <ExclusiveMenuItem:ExclusiveMenuItem Header="OneDecimal" IsCheckable="True" IsChecked="{Binding Path=DecimalPlaces}"/>
    <ExclusiveMenuItem:ExclusiveMenuItem Header="TwoDecimal" IsCheckable="True" IsChecked="{Binding Path=DecimalPlaces}"/>
</MenuItem>

If it needs some data coming from your MenuItems, then use an ItemTemplate or ItemContainerStyle.

<MenuItem Header="{DynamicResource DecimalPlaces}" ItemsSource="{Binding MenuItems}">
    <MenuItem.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Header" Value="{Binding SomeProperty}" />
            <Setter Property="IsCheckable" Value="True" />
            <Setter Property="IsChecked" Value="{Binding Path=DecimalPlaces}" />
        </Style>
    </MenuItem.ItemContainerStyle>
</MenuItem>

Upvotes: 1

Related Questions