问题描述
我有一个带有状态"的可观察集合的自定义控件,有点像多状态按钮.这里只有必要的代码,以避免造成混淆:
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; }
}
}
"MyState"类(集合中的objets)包含一个公共的"Name"属性,我想在每个自定义控件的位置上方显示该属性.
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.
现在.在窗口的XAML中,我创建了2个MyMultiStateBtn实例,其中一个看起来像这样(显然,第二个实例具有不同的状态"列表):
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>
到目前为止,一切都很好.请注意,这些控件使用的是模板("MultiStateBtnTpl").这个模板使用TextBoxes显示状态名称...这就是我在语法中迷失的地方.我将为您避免我数百万次失败的尝试……这大致就是我的初衷(请注意:我知道此绑定无效!):
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).
在此先感谢您的帮助!
Seb
PS:我可以创建3个单独的属性,并在controltemplate中访问它们.但是,在某些情况下,最多可能有10个甚至20个职位.我要避免拥有20个单独的属性.
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.
推荐答案
尝试使用RelativeSource
绑定
<TextBlock x:Name="RelativeSourceBinding"
Text="{Binding States[0].Name,
RelativeSource={AncestorType local:MyMultiStateBtn}}" />
这篇关于如何将特定的ObservableCollection项的属性绑定到CustomControl的ControlTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!