簡體   English   中英

獲取WPF控件以觸發並設置另一個控件的itemssource

[英]Getting a WPF control to trigger and set another control's itemssource

我正在開發一個WPF應用程序,我想在這里展示一個有兩個選項的ComboBox。 根據第一個ComboBox中的選擇,第二個ComboBox的ItemsSource應該更改為顯示在第一個ComboBox中選擇的類型的項目。

但是,我的方法遇到了一些循環問題。 我是WPF和MVVM的新手,所以也許我錯過了一些明顯的東西。 我在互聯網上找到的(很多)例子都不適用於我的情況。

我的XAML代碼:

<ComboBox x:Name="cmbTargetType" SelectionChanged="cmbTargetType_SelectionChanged">
 <Style TargetType="ComboBox">
  <Style.Triggers>
   <Trigger Property="Text" Value="Materials">
    <Setter TargetName="cmbTarget" Property="ItemsSource" Value="{Binding DataContext.MaterialListViewModel.MaterialViewModels.AllMaterials, RelativeSource={RelativeSource AncestorType=Window}}"></Setter>
   </Trigger>
   <Trigger Property="Text" Value="ProductParts">
    <Setter TargetName="cmbTarget" Property="ItemsSource" Value="{Binding DataContext.ProductViewModel.ProductPartViewModels.AllProductParts, RelativeSource={RelativeSource AncestorType=Window}}"></Setter>
   </Trigger>
  </Style.Triggers>
 </Style>
 <ComboBoxItem Content="Material"/>
 <ComboBoxItem Content="ProductPart"/>
</ComboBox>

此代碼給出了錯誤“無法在樣式設置器上設置TargetName屬性”。 我假設是因為樣式中沒有可用的DataContext。 但是,當我從代碼中刪除Style元素時,我最終會遇到更多錯誤。 它似乎沒有識別屬性'Text'和'ItemsSource',在“ContentPresenter”類型上給出錯誤“找不到靜態成員'TextProperty'。” 在互聯網上尋找這個錯誤的答案,我找到的唯一答案就是把觸發器放在一個風格中......

我在這做錯了什么?

無法在Style觸發器中設置TargetName 您可以綁定到其他ComboBox的屬性,如下所示

<StackPanel>
  <ComboBox x:Name="cmbTargetType" SelectionChanged="cmbTargetType_SelectionChanged">
    <ComboBoxItem Content="Material"/>
    <ComboBoxItem Content="ProductPart"/>
  </ComboBox >
  <ComboBox x:Name="cmbTarget">
    <ComboBox.Style>
      <Style TargetType="{x:Type ComboBox}">
        <Style.Triggers>
          <DataTrigger Binding="{Binding Text, ElementName=cmbTargetType}"
              Value="Material">
            <Setter Property="ItemsSource"
                Value="{Binding 
                  DataContext.MaterialListViewModel.MaterialViewModels.AllMaterials, 
                  RelativeSource={RelativeSource AncestorType=Window}}" />
          </DataTrigger>
          <DataTrigger Binding="{Binding Text, ElementName=cmbTargetType}"
              Value="ProductPart">
            <Setter Property="ItemsSource"
                Value="{Binding 
                  DataContext.ProductViewModel.ProductPartViewModels.AllProductParts, 
                  RelativeSource={RelativeSource AncestorType=Window}}" />
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </ComboBox.Style>
  </ComboBox>
</StackPanel>

@David這可以使用TargetedTriggerAction實現。 但你必須寫一些代碼。 在MVVM中使用TargetedTriggerAction是可接受的。 http://www.codeproject.com/Tips/401707/Behavior-and-Trigger-in-WPF-Silverlight

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM