开发者

Changing UserControl background based on SelectedValue from combobox

开发者 https://www.devze.com 2022-12-19 02:27 出处:网络
What I try to do: I have a list of person profiles in the background that I use with my combobox. The trigger is to change the background based on the gender of the person (bool Role.IsFemale). When I

What I try to do: I have a list of person profiles in the background that I use with my combobox. The trigger is to change the background based on the gender of the person (bool Role.IsFemale). When I handle the SelectionChangedEvent in the code, I can see the Selectedvalue is true or false. I could now change the background directly or change a dependencyProperty to which the usercontrol itself could listen and change the background when triggered. However, what I try is to just use xaml to achieve this, but nothing happens when I use the code below...

<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>
开发者_StackOverflow        <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>


I tried your Xaml and it works fine for me, when I change the combo box, it changes the background. Perhaps there is something wrong with your data binding. I used the following data structure

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

    public Role() {}
}

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

    public Person() {}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消