gpt4 book ai didi

c# - 将 UserControl 中元素的属性绑定(bind)到 MyViewModel.cs 中的属性

转载 作者:行者123 更新时间:2023-12-03 10:23:02 26 4
gpt4 key购买 nike

首先,我对 MVVM 的概念非常陌生。我什至不确定我在这里问的是一个 MVVM 问题。所以请原谅我在这里可能犯的错误。

我正在尝试 Bind Foreground TextBlock 的属性(property)在 UserControlTextColor位于 MyViewModel.cs 的属性(property).我还希望能够更改 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;
}
}

最佳答案

您的 MyViewModel类应该声明一个公共(public) TextColor属性,而不是公共(public)字段(您可以将其重命名为 TextBrush,因为它是画笔,而不是颜色)。为了能够通知属性值的变化,它还应该实现 INotifyPropertyChanged 接口(interface)。

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;
}

更改颜色的更好解决方案是绑定(bind) Button 的 Command属性到 ICommand在您的 View 模型中。您可以在 Commanding Overview 中开始阅读此内容。 MSDN 上的文章。

关于c# - 将 UserControl 中元素的属性绑定(bind)到 MyViewModel.cs 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com