Bind the property of an element in UserControl to

2019-10-20 13:35发布

首先,我非常非常新的MVVM的概念。 我甚至不知道我要问这里甚至有一个MVVM问题。 所以,请原谅我的错误,我可以在这里做。

我想BindForeground一个财产TextBlockUserControlTextColor物业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;
    }
}

Answer 1:

MyViewModel类应该声明公共TextColor属性,而不是公共领域(你可以将其重命名为TextBrush ,因为它是一个刷机,而不是颜色)。 为了能够通知有关的属性值的变化,还应该实现INotifyPropertyChanged接口。

public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Brush textColor = Brushes.Red;
    public Brush TextColor
    {
        get { return textColor; }
        set
        {
            textColor = value;
            RaisePropertyChanged("TextColor");
        }
    }

    private void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

在您的按钮单击处理你现在可以施放DataContext你MyViewModel类,并设置属性。

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    var vm = (MyViewModel)DataContext;
    vm.TextColor = Brushes.Blue;
}

一个更好的解决方案来改变颜色将是按钮的绑定Command属性设置为一个ICommand在您的视图模型。 你可以开始阅读关于这个指挥概况 MSDN上的文章。



文章来源: Bind the property of an element in UserControl to a property in MyViewModel.cs
标签: c# wpf xaml mvvm