How to Bind a specific ObservableCollection item's property to a CustomControl's ControlTemplate

穿精又带淫゛_ 提交于 2019-12-23 05:12:33

问题


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.


回答1:


Try using a RelativeSource binding

<TextBlock x:Name="RelativeSourceBinding" 
           Text="{Binding States[0].Name, 
               RelativeSource={AncestorType local:MyMultiStateBtn}}" />


来源:https://stackoverflow.com/questions/8053873/how-to-bind-a-specific-observablecollection-items-property-to-a-customcontrols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!