WPF:根据绑定值更改 ItemsControl 中的样式
WPF: Changing styles within ItemsControl based on binding values
我有一个看起来像这样的 ItemsControl:
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}" />
<Slider Value="{Binding Volume}" />
<Slider Value="{Binding Pan}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
绑定如下:
ObservableCollection<UserSettings> connectedUserSettings = new ObservableCollection<UserSettings>();
DataContext = connectedUserSettings;
其中 UserSettings
看起来像这样:
public class UserSettings
{
public string Name;
public int Volume;
public float Pan;
public bool Audible;
public bool UserIsSpeaking;
}
当 UserIsSpeaking
为 true
时,我想将 Name TextBlock 的背景更改为 "Lime"。当 Audible
为 false
时,我还想禁用 Slider 控件。最好的方法是什么?在 XAML?
中有使用样式或其他内容的简单方法吗?
您可以直接绑定滑块并使用下面的触发器来更改 TextBlock 的背景。还要确保您要绑定的 Collection 应该是 属性 而不是字段。与 UserSettings class 相同,公开属性而不是字段并实现 INotifyPropertyChanged 接口,如果你想在运行时根据 属性 更改
更改 UI
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock x:Name="myTextBlock" Text="{Binding Name}" />
<Slider IsEnabled="{Binding Audible}" Value="{Binding Volume}" />
<Slider IsEnabled="{Binding Audible}" Value="{Binding Pan}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding UserIsSpeaking}" Value="True">
<Setter TargetName="myTextBlock" Property="Background" Value="Lime"></Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我有一个看起来像这样的 ItemsControl:
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}" />
<Slider Value="{Binding Volume}" />
<Slider Value="{Binding Pan}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
绑定如下:
ObservableCollection<UserSettings> connectedUserSettings = new ObservableCollection<UserSettings>();
DataContext = connectedUserSettings;
其中 UserSettings
看起来像这样:
public class UserSettings
{
public string Name;
public int Volume;
public float Pan;
public bool Audible;
public bool UserIsSpeaking;
}
当 UserIsSpeaking
为 true
时,我想将 Name TextBlock 的背景更改为 "Lime"。当 Audible
为 false
时,我还想禁用 Slider 控件。最好的方法是什么?在 XAML?
您可以直接绑定滑块并使用下面的触发器来更改 TextBlock 的背景。还要确保您要绑定的 Collection 应该是 属性 而不是字段。与 UserSettings class 相同,公开属性而不是字段并实现 INotifyPropertyChanged 接口,如果你想在运行时根据 属性 更改
更改 UI<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock x:Name="myTextBlock" Text="{Binding Name}" />
<Slider IsEnabled="{Binding Audible}" Value="{Binding Volume}" />
<Slider IsEnabled="{Binding Audible}" Value="{Binding Pan}" />
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding UserIsSpeaking}" Value="True">
<Setter TargetName="myTextBlock" Property="Background" Value="Lime"></Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>