繁体   English   中英

如何在WPF中访问控件模板内的组合框?

[英]How to access combobox inside control template in WPF?

我有一个定义如下的控制模板:

<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中定义控件模板时如何使用它?

您可以使用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}}" >

并在代码背后填充数据:

CollectionViewSource yourView = ((CollectionViewSource)(this.FindResource("ViewName")));

yourView.Source = yourCollection;

首先,当已经有绑定来支持模板时,从后面的代码访问模板并设置其属性不是一个好习惯。

现在,即使您想这样做, FindName()也是一种解决方法。 您需要从应用此资源的控件访问模板。

假设您有这样声明的comboBox:

<ComboBox x:Name="cmb" Template="{StaticResource fiscalItemsControlTemplate}"/>

您可以像下面这样从后面的代码访问:

var comboBox = cmb.Template.FindName("cbOrderState", cmb);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM