首先,我非常非常新的MVVM的概念。 我甚至不知道我要问这里甚至有一个MVVM问题。 所以,请原谅我的错误,我可以在这里做。
我想Bind
的Foreground
一个财产TextBlock
在UserControl
来TextColor
物业MyViewModel.cs
。 我也希望能够改变TextColor
通过代码属性。 例如通过点击按钮。 如何能够做到所有这一切。
下面是完整的非工作无差错代码到目前为止,我忍了!
主窗口:
<Window x:Class="WpfApplication23.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"
xmlns:local="clr-namespace:WpfApplication23">
<StackPanel>
<local:UserControl1 x:Name="MyControl"/>
<Button Content="Change Color"
Width="200"
Height="30"
Click="ButtonBase_OnClick"/>
</StackPanel>
</Window>
MainWindow.xaml.cs:
using System.Windows;
namespace WpfApplication23
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
// Change the `TextColor` property in `MyViewModel.cs`
}
}
}
用户控件:
<UserControl x:Class="WpfApplication23.UserControl1"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid>
<TextBlock Text="Sample Text" Foreground="{Binding TextColor}"/>
</Grid>
</UserControl>
MyViewModel.cs:
public class MyViewModel
{
public Brush TextColor;
public MyViewModel()
{
TextColor = Brushes.Red;
}
}