Question

I have a custom control with an observable-collection of "states", sort of like a multiple-state-button. Only the necessary code is here to avoid confusion:

public class MyMultiStateBtn : ItemsControl
{
    MyMultiStateBtn()
    {
       m_states = new ObservableCollection<MyState>();
    }

    private ObservableCollection<MyState> m_states;
    public System.Collections.ObjectModel.ObservableCollection<MyState> States
    {
       get { return m_states; }
       set { m_states = value; }
    }
}

The "MyState" class (the objets in the collection) contains a public "Name" property that I want to display above each my custom control's positions.

Now. In the window's XAML, I created 2 instances of MyMultiStateBtn, where one of them looks like this (the second one has different list of "states", obviously):

<local:MyMultiStateBtn x:Name="AAA" Template="{StaticResource MultiStateBtnTpl}">
    <local:MyMultiStateBtn.States>
        <local:MyState Name="On"/>
        <local:MyState Name="Off" Value="1"/>
        <local:MyState Name="Auto" Value="2"/>
    </local:MyMultiStateBtn.States>
</local:MyMultiStateBtn>

So far so good. Notice these controls are using a template ("MultiStateBtnTpl"). This template uses TextBoxes to display the state names... and that's where I got lost in the syntax. I'll spare you my million-failed attempts... here's roughly what I had in mind (note: I know this binding does NOT work!):

<ControlTemplate x:Key="MultiStateBtnTpl" TargetType="{x:Type loca:MyMultiStateBtn}">
    <Grid Width="130" Height="120">
        <TextBlock x:Name="tkValue1" Text="{Binding States, Path=[0].Name}" />
        <TextBlock x:Name="tkValue2" Text="{Binding States, Path=[1].Name}" />
        <TextBlock x:Name="tkValue3" Text="{Binding States, Path=[2].Name}" />
    </Grid>
</ControlTemplate>

In a nutshell: How can I make the template find the strings buried within the items of an observable collection...

I know the information is out there, but nothing I found helped me access data within individual elements of an array (collection).

Thanks in advance for any help!

Seb

PS: I could create 3 seperate properties, and access those in the controltemplate. However, in some cases there could be up to 10, or even 20 positions. I want to avoid having 20 separate properties.

Was it helpful?

Solution

Try using a RelativeSource binding

<TextBlock x:Name="RelativeSourceBinding" 
           Text="{Binding States[0].Name, 
               RelativeSource={AncestorType local:MyMultiStateBtn}}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top