我有一个如下定义的控件模板:
<Window.Resources>
<ControlTemplate x:Key="fiscalItemsControlTemplate">
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="17" />
<RowDefinition Height="19" />
<RowDefinition Height="17" />
<RowDefinition Height="19" />
<RowDefinition Height="17" />
<RowDefinition Height="19" />
</Grid.RowDefinitions>
<Label Padding="0" Grid.Row="0" Content="{DynamicResource AmmountStr}" HorizontalAlignment="Left" Name="lblAmmount" VerticalAlignment="Bottom" Height="17"/>
<TextBox Padding="0" Name="txtAmmount" Grid.Row="1" Height="19" Width="189" HorizontalAlignment="Left" VerticalAlignment="Bottom" Text="{Binding Path=Amount, Converter={StaticResource moneyConverter}}" />
<Label Padding="0" Content="PurchasePrice" Grid.Row="2" Grid.RowSpan="2" Height="17" HorizontalAlignment="Left" Name="lblPurchasePrice" VerticalAlignment="Top" />
<TextBox Padding="0" Grid.Row="3" Grid.RowSpan="2" Height="19" HorizontalAlignment="Left" Name="txtPurchasePrice" VerticalAlignment="Top" Width="189" Text="{Binding Path=PurchasePrice, Converter={StaticResource moneyConverter}, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnSourceUpdated=True}" Validation.Error="Validation_Error" PreviewTextInput="NumericOnly" />
<Label Padding="0" Grid.Row="4" Name="lblOrderState" HorizontalAlignment="Left" Content="Order State" Height="17" />
<ComboBox Padding="0" Grid.Row="5" HorizontalAlignment="Left" Name="cbOrderState" Height="19" Width="189" >
</ComboBox>
</Grid>
</ControlTemplate>
</Window.Resources>
我要做的是在代码隐藏中访问组合框“cbOrderState”并在那里声明它的itemssours。我知道FindName()方法有一些方法,但是当在Window.Resources中定义控件模板时如何使用它?
答案 0 :(得分:1)
您可以使用CollectionViewSource:
<Window.Resources>
<CollectionViewSource x:Key="ViewName"/>
</Window.Resources>
并在你的组合框中使用:
<ComboBox Padding="0" Grid.Row="5" HorizontalAlignment="Left" Name="cbOrderState" Height="19" Width="189" ItemsSource="{Binding Source={StaticResource ViewName}}" >
并在codebehind中填充数据:
CollectionViewSource yourView = ((CollectionViewSource)(this.FindResource("ViewName")));
yourView.Source = yourCollection;
答案 1 :(得分:0)
首先,当你已经有绑定支持时,访问模板并从代码中设置它的属性并不是一个好习惯。
现在,即使您想要这样做, FindName()
也是一种方法。您需要从应用此资源的控件访问模板。
假设你有这样声明的comboBox:
<ComboBox x:Name="cmb" Template="{StaticResource fiscalItemsControlTemplate}"/>
您可以从后面的代码访问,如下所示:
var comboBox = cmb.Template.FindName("cbOrderState", cmb);