2014-03-07 70 views
0

我有這樣定義的控件模板:如何訪問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中定義控件模板時如何使用它?

回答

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}}" > 

,並在代碼隱藏填充數據:

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

yourView.Source = yourCollection; 
+0

很不錯的。謝謝! – Stojdza

0

首先,這不是一個好練習訪問模板,並在你已經綁定已經支持的時候,從代碼背後設置它的屬性噸。

現在,即使萬一你想這樣做FindName()是一種方式。您需要從應用此資源的控件訪問模板。

假設你有一個組合框聲明如下:

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

您可以從代碼中訪問的背後是這樣的:

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