2010-02-05 32 views
1

我試圖做的是:我在我的組合框中使用了背景中的人員配置文件列表。觸發器是根據人的性別改變背景(bool Role.IsFemale)。當我在代碼中處理SelectionChangedEvent時,我可以看到Selectedvalue是true或false。我現在可以直接更改背景或更改用戶控件本身可以偵聽的dependencyProperty,並在觸發時更改背景。不過,我嘗試是隻使用XAML來實現這一點,但是當我使用下面的代碼沒有任何反應......基於組合框的SelectedValue更改UserControl背景

<UserControl ... 
MinHeight="100" MinWidth="100" x:Name="Crtl"> 
<UserControl.Resources> 
    <SolidColorBrush x:Key="windowBGBrush1" Color="Green"/> 
    <SolidColorBrush x:Key="windowBGBrush2" Color="Red"/> 
</UserControl.Resources> 
<UserControl.Style > 
    <Style TargetType="{x:Type Control}"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding Path=SelectedValue, ElementName=cbProfiles}" Value="False"> 
       <Setter Property="Background" Value="{DynamicResource windowBGBrush1}"/> 
      </DataTrigger> 
      <DataTrigger Binding="{Binding Path=SelectedValue, ElementName=cbProfiles}" Value="True"> 
      <Setter Property="Background" Value="{DynamicResource windowBGBrush2}"/> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 
</UserControl.Style> 
<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="20*"/> 
     <RowDefinition Height="80*" /> 
    </Grid.RowDefinitions> 
    <ComboBox Name="cbProfiles" Grid.Row="0" ItemsSource="{Binding}" DisplayMemberPath="Role.RoleID" SelectedValuePath="Role.IsFemale"/> 
    <StackPanel Grid.Row="1" x:Name="spFileInfo" DataContext="{Binding ElementName=cbProfiles, Path=SelectedItem}"> 
     <TextBlock>Selected:</TextBlock> 
     <TextBox x:Name="tbFileFolder" Width="Auto" Height="Auto" Text="{Binding Path=Role.RoleID}"/> 
    </StackPanel> 
</Grid> 

回答

0

我想你的XAML和它爲我工作得很好,當我更改組合框,它會更改背景。也許你的數據綁定有問題。我用了下面的數據結構

class Role 
{ 
    public int RoleID { get; set; } 
    public bool IsFemale { get; set; } 

    public Role() {} 
} 

class Person 
{ 
    public Role Role { get; set; } 

    public Person() {} 
} 
+0

好的,我在一個新的項目中自己試了一下,並直接將我的代碼添加到主窗口:它的工作原理,背景變化! 在我使用UserControl之前,將此控件添加到窗口中。我看到控件並可以使用它,但背景不會改變。 任何人都可以解釋這種行爲?對我來說會很有趣,因爲我經常開發UserControls,我可以在不同的項目中重複使用... – 2010-02-06 17:58:52

+0

然後,由於我實際上在我的一個項目中測試了Xaml,所以在UserControl – Thomas 2010-02-06 19:04:49