我是WPF技术的新手。我正在使用MVVM架构。 我想根据viewmodel的属性更改textblock的背景。 例如,如果我使用'brush'对象,我想将它绑定到textblock的背景颜色。
<TextBlock Margin="0,1"
HorizontalAlignment="Center"
FontFamily="Arial"
FontSize="16"
Text="{Binding Line}"
TextWrapping="Wrap"
Background="{Binding brushobj}"/>
如何实施?
答案 0 :(得分:2)
您可以在ViewModel中定义它。
private Brush _brushobj;
/// <summary>
/// Gets or sets the BrushObject.
/// </summary>
public Brush BrushObj
{
get
{
return _brushobj;
}
set
{
// Set value
_brushobj = value;
// Notify UI that the value has changed.
RaisePropertyChanged("BrushObj");
// OnPropertyChanged("BrushObj"); // Use the appropriate function to notify the UI.
}
}
然后只需使用以下内容设置值:
BrushObj = (Brush)new BrushConverter().ConvertFromString("Green");
最后,您将其绑定到View,就像在问题中所做的那样:
Background="{Binding BrushObj}"
编辑:我试图自己创建一个项目只是为了验证这确实有效,并且以下代码工作正常。如果它仍然不能正常工作,那么更有可能是你的MVVM设置导致问题。
<强> MainWindowViewModel:强>
namespace WpfApplication1
{
public class MainWindowViewModel : ObservableObject
{
private Brush _brushobj = (Brush)new BrushConverter().ConvertFromString("Red");
public Brush BrushObj
{
get
{
return _brushobj;
}
set
{
_brushobj = value; // Set value
RaisePropertyChanged("BrushObj"); // Notify UI that the value has changed.
}
}
}
}
<强>主窗口:强>
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Margin="0,1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
FontFamily="Arial"
FontSize="16"
Text="Testing a lot of stuff here! important stuff!"
TextWrapping="Wrap"
Background="{Binding BrushObj}"/>
</Grid>
</Window>