在XAML中ControlTemplate中定义的元素的访问属性 [英] Access properties of elements defined in ControlTemplate in xaml
问题描述
在我的XAML我已经把定义为10项:
in my xaml I have to put 10 items defined as:
<StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="1">
<TextBox Width="100"
DataContext="{StaticResource dataProvider}"
Text="{Binding XPath='BLOCK[@id=2]/ITEMS/ITEM[@id=1]/@value'}"/>
<ComboBox Margin="5"
DataContext="{StaticResource dataProvider}"
SelectedValuePath="Tag"
SelectedValue="{Binding XPath='BLOCK[@id=2]/ITEMS/ITEM[@id=2]/@value'}">
<ComboBoxItem Content="GROUP" Tag="6" />
<ComboBoxItem Content="PRIVATE" Tag="5" />
</ComboBox>
<TextBox Width="200"
DataContext="{StaticResource dataProvider}"
Text="{Binding XPath='BLOCK[@id=2]/ITEMS/ITEM[@id=4]/@value'}"/>
</StackPanel>
因此,而不是重复了很多次,我想用这样的控件模板>
So, instead of repeat it many times, I thought to use a ControlTemplate like this:
<DataTemplate.Resources>
<ControlTemplate x:Key="AddressItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBox Name="Address" Width="200"/>
<ComboBox Name="Type">
<ComboBoxItem Content="GROUP" Tag="6" />
<ComboBoxItem Content="PRIVATE" Tag="5" />
</ComboBox>
<TextBox Name="Description" Width="200"/>
</StackPanel>
</ControlTemplate>
</DataTemplate.Resources>
现在,当我使用它...
Now when I use it...
<Control Grid.Row="0" Grid.Column="1" Template="{StaticResource AddressItemTemplate}" />
<Control Grid.Row="1" Grid.Column="1" Template="{StaticResource AddressItemTemplate}" />
<Control Grid.Row="2" Grid.Column="1" Template="{StaticResource AddressItemTemplate}" />
..因为XPath的绑定属性是每个项目(ITEM [@Id]的变化总是不同的),我需要一种方法,当我创建了控制访问TextBox.Text,ComboBox.SelectedValuePath和ComboBox.SelectedValue属性。
.. since the XPath binding property is different for each item (the ITEM[@Id] changes always), I need a way to access the TextBox.Text, ComboBox.SelectedValuePath and ComboBox.SelectedValue property when I create the 'Control'.
有没有办法做到呢?
推荐答案
这是WPF中一个很普遍的问题。如果你命名你的控制
控件,你可以访问这些元素
是这样的:
This is a very common question in WPF. You can access these elements if you named your Control
control
like this:
TextBox textBox = (TextBox)control.Template.FindName("Address", control);
ComboBox comboBox = (ComboBox)control.Template.FindName("Type", control);
我相信,你可以工作,其余为你自己。
I trust that you can work the rest out for yourself.
这篇关于在XAML中ControlTemplate中定义的元素的访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!