我是一个巨大的 XAML 菜鸟,我正在使用 MVVM 构建一个 WinRT 应用程序。基本上,我有一个返回 SolidColorBrush 的函数 getBackgroundColor(),并且我想使它在任何给定时间都可以更改背景颜色,并通知 XAML 元素并进行更改以匹配 getBackgroundColor 的新输出。我知道这应该通过绑定(bind)来完成,但并不真正了解任何在线文档。有人可以像我 5 岁那样向我解释这个吗?
最佳答案
Flip 的答案是教科书式的答案,很可能会达到您想要的结果。通常对我来说,我发现 MVVM 是学术界与现实世界的持续实践。遵循 MVVM 模式适用于您的场景,但还有其他方法可以更改 UI 颜色。这就是谈话的开始。 ViewModel 是否需要知道 View 如何显示您正在显示的内容?如果是,请坚持另一个答案。如果不是,则在 View 中拍打它(您的 window.xaml 和 window.xaml.cs)
例如,我有一个我使用的颜色转换器,因为我决定我的 ViewModel 不需要知道我在 View 中切换的颜色。所以在 View xaml.cs 中(或者实际上你可以在任何地方声明它,因为它是一个类)我定义了:
/// <summary>
/// A way to convert the color of text based upon maintenance required
/// </summary>
public class MaintenenceColorConverter : IValueConverter
{
#region Properties
// Properties
public Color NormalColor { get; set; }
public Color NoMaintenanceRequiredColor { get; set; }
#endregion
/// <summary>
/// DEFAULT CONSTRUCTOR
/// </summary>
public MaintenenceColorConverter() { }
/// <summary>
/// Convert the color of the text based upon maintenance required
/// </summary>
/// <returns>
/// The appropriate color property
/// </returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.ToString() == "No Maintenance Required") return NoMaintenanceRequiredColor.ToString();
return NormalColor.ToString();
}
/// <summary>
/// Not used: NECESSARY FOR IMPLEMENTATION
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
}
}
现在这并不漂亮,因为我觉得我通过在 View 中检查 View 模型的数据有点违反 MVVM 设计模式,但我可以接受(让火焰开始吧!)。
因此,此时您需要在 xaml 中做的就是定义颜色转换器:
<UserControl.Resources>
<localColor:MaintenenceColorConverter x:Key="MyColorConverter" NormalColor="Black" NoMaintenanceRequiredColor="Gray" />
</UserControl.Resources>
然后在需要的地方使用它!我在数据网格中使用它来“灰色”选择:
<DataGrid.Columns>
<DataGridTextColumn Header="Site Number" Binding="{Binding Path=SiteNo}" IsReadOnly="True" Width="100">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="Foreground" Value="{Binding Path=MaintStatus, Converter={StaticResource MyColorConverter}}" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGrid.Columns>
干杯!
关于c# - View 在屏幕上时如何修改 XAML 元素的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26661429/