Tôi đã thực hiện việc này bằng cách sử dụng trình chuyển đổi đơn giản trên thuộc tính của mô hình chế độ xem, ví dụ: giả sử bạn có thuộc tính boolean mà bạn muốn kiểm soát kiểu bạn có thể thực hiện việc này.
public class BoolToStyleConverter : IValueConverter
{
public Style TrueStyle{ get; set; }
public Style FalseStyle{ get; set; }
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((bool)value) ? TrueStyle : FalseStyle;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
sau đó như một nguồn lực bạn sẽ xác định hai phong cách của bạn ...
<common:BoolToStyleConverter x:Key="BoldTextConverter">
<common:BoolToStyleConverter.TrueStyle>
<Style TargetType="TextBlock">
<Setter Property="FontWeight"
Value="Bold"></Setter>
</Style>
</common:BoolToStyleConverter.TrueStyle>
<common:BoolToStyleConverter.FalseStyle>
<Style TargetType="TextBlock">
<Setter Property="FontWeight"
Value="Normal"></Setter>
</Style>
</common:BoolToStyleConverter.FalseStyle>
</common:BoolToStyleConverter>
sau đó bạn sẽ áp dụng nó để đối tượng của bạn như thế này ...
<TextBlock Text="{Binding Description}"
Margin="20,4,4,4"
Style="{Binding IsConfirmed, Converter={StaticResource BoldTextConverter}}"></TextBlock>
đâu IsConfirmed là một thuộc tính boolean trên viewmodel, điều này cũng sẽ giữ cho kiểu đồng bộ nếu thay đổi thuộc tính IsConfirmed
.
Nếu bạn muốn sử dụng điều kiện phức tạp hơn Boolean, bạn luôn có thể tạo từ điển đối tượng cho kiểu dáng trong trình chuyển đổi của mình và sau đó chuyển trình tìm kiếm, nhưng tôi thấy rằng boolean thường hoạt động trong hầu hết các trường hợp.
Làm cho cảm giác hoàn hảo, cổ vũ! – deanvmc