【发布时间】:2014-09-22 14:42:20
【问题描述】:
我有一个嵌套列表框(另一个列表框内的列表框)。我想为突出显示/选定的列表框项以及字体粗细设置前景色属性。颜色和字体粗细的值是从 xml 文件中读取的。 SelectedItemForegroundColor 和 SelectedItemFontWeight 属性在执行视图模型构造函数时设置为字符串。这些属性只设置一次,以后不会更改,除非更新 xml 文件中的值并重新启动应用程序。
这是该问题的 XAML 代码 sn-p。
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="White"/>
</Style.Resources>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="{Binding SelectedItemForegroundColor, Converter={StaticResource stringToBrushConverter}}"/>
<Setter Property="FontWeight" Value="{Binding SelectedItemFontWeight}"/>
</Trigger>
</Style.Triggers>
</Style>
<ListBox ItemsSource="{Binding ItemsList}" SelectedItem="{Binding SelectedResultItem}" SelectionChanged="OnListBoxSelectionChanged" Background="White" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,5">
<ListBox ItemsSource="{Binding InnerItems}" BorderThickness="0" Background="White"
Foreground="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LabelName}" Margin="0,0,5,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这是用于在视图模型初始化期间设置前景色的属性。
public string SelectedItemForegroundColor
{
get
{
return this.selectedItemForegroundColor;
}
set
{
this.selectedItemForegroundColor = value;
this.RaisePropertyChanged(() => this.SelectedItemForegroundColor);
}
}
public string SelectedItemFontWeight
{
get
{
return this.selectedItemFontWeight;
}
set
{
this.selectedItemFontWeight = value;
this.RaisePropertyChanged(() => this.SelectedItemFontWeight);
}
}
字符串转刷转换器类:
每当调用转换器时,对象值为空字符串“”。调试时我发现属性 SelectedItemForegroundColor 值不为空。我已经分配了 Green 并且它仍然将这个值保持为 Green 。
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var brush = DefaultBrush;
if (!string.IsNullOrEmpty(value.ToString()))
{
var color = Color.FromName(value.ToString());
brush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(color.A, color.R, color.G, color.B));
}
return brush;
}
属性的值未分配给背景。我还需要知道我们应该使用什么转换器来更改字体的字体粗细。
提前致谢
【问题讨论】:
-
很明显,你用错了
Binding Path。您的两个属性在哪里声明,这个 XAML 在哪里声明? -
SelectedResultItemForegroundColor和SelectedItemForegroundColor拼写不同,这是有意还是无意? -
@Netscape:对不起,属性名称是 SelectedItemForegroundColor 不是 SelectedResultItemForegroundColor。另一个属性是 SelectedItemFontWeight。
-
@Sheridan:属性在视图模型中声明,XAML 在视图中声明。