2013-03-15 125 views
2

我是WPF的新手,請耐心等待。我在我的WPF窗口上有一個ComboBox,ItemSource屬性綁定到一個字符串屬性列表(國家)和SelectedItem綁定到一個字符串屬性(SelectedCountry)。這兩個屬性都在代碼後面 - 我將DataContext設置爲「this」(即Window)。WPF默認值(使用樣式觸發器)綁定

組合框XAML是:

<ComboBox Name="CountryComboBox" 
    VerticalAlignment="Center" 
    Width="200" 
    ItemsSource="{Binding Path=Countries, Mode=OneTime}" 
    SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}"> 
</ComboBox> 

我想有一個默認的「 - 請選擇 - 」時未選擇項目時顯示的選項,因此我把下面的XAML中的App.xaml:

<Style TargetType="ComboBox"> 
    <Style.Triggers> 
     <Trigger Property="SelectedItem" Value="{x:Null}"> 
      <Setter Property="IsEditable" Value="true" /> 
      <Setter Property="IsReadOnly" Value="true" /> 
      <Setter Property="Text" Value="- Please Select -" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

當我的窗口第一次顯示時,組合框確實有「 - 請選擇 - 」文本按預期。然後,當我在組合框中選擇一個值時,SelectedCountry被適當填充,但是當我將SelectedCountry屬性賦值爲「null」時,當我期望它返回到「 - 請選擇 - 」。我究竟做錯了什麼?

謝謝。

+0

嘗試添加了當 ComboBox.SelectedValue == NULL觸發 – 2013-03-15 18:37:20

回答

4

SelectedItem爲空時,不要修改ComboBox並簡單地覆蓋ComboBox上的TextBlock可能是更好的選擇。

只是包裝的ComboBox並在Grid一個TextBlock並設置DataTriggerTextBlock來檢查SelectedItem爲null並且切換其Visibility

例子:

<Grid> 
     <ComboBox x:Name="combo" ItemsSource="{Binding Countries}" SelectedItem="{Binding SelectedItem}" /> 
     <TextBlock x:Name="textblock" Text="- Please Select -" Margin="5,3,0,0" IsHitTestVisible="False"> 
      <TextBlock.Style> 
      <Style TargetType="TextBlock"> 
        <Setter Property="Visibility" Value="Hidden" /> 
        <Style.Triggers> 
         <DataTrigger Binding="{Binding SelectedItem,ElementName=combo}" Value="{x:Null}"> 
          <Setter Property="Visibility" Value="Visible" /> 
         </DataTrigger> 
        </Style.Triggers> 
       </Style> 
      </TextBlock.Style> 
     </TextBlock> 
    </Grid> 

結果:

enter image description here

enter image description here

enter image description here

1

你需要插入一條記錄到具有的空值和名字的名單的國家「 - 請選擇 - 」。

另外我想你可以延長ComboBox控件,寫自己的,這樣你可以不必把記錄到國家選擇指定列表中的空谷。

兩個,但是,它是非常容易,只是一個記錄添加到多個國家。