c# - 如何将前景绑定(bind)到我的 ViewModel 中的属性?

标签 c# wpf mvvm

我想将 TextBlock 的前景属性绑定(bind)到我的 ViewModel 中的属性。

这行不通:

编辑

View :

TextBlock 
Text="{Binding Path=FullName, Mode=OneWay}" 
Foreground="{Binding Path=ForegroundColor}"
Margin="0 5 3 5"

代码隐藏:

CustomerHeaderViewModel customerHeaderViewModel = new CustomerHeaderViewModel();
customerHeaderViewModel.LoadCustomers();
CustomerHeaderView.DataContext = customerHeaderViewModel;

查看模型:

private System.Windows.Media.Brush _foregroundColor;
_foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

public System.Windows.Media.Brush ForegroundColor
{
    get { return _foregroundColor; }
    set { _foregroundColor = value; 
        OnPropertyChanged("ForegroundColor");
    }
}

public CustomerHeaderViewModel()
{
ForegroundColor = System.Windows.Media.Brushes.Red;
}

所有其他属性(文本等)正确绑定(bind)。

我做错了什么?

最佳答案

检查你的解决方案是否是这样的: 查看:

<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:vm="clr-namespace:WpfApplication13"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:MainVM/>
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding Path=FullName, Mode=OneWay}" 
                   Foreground="{Binding Path=ForegroundColor}"
                   Margin="0 5 3 5"/>
    </Grid>
</Window>

View 模型:

public class MainVM : INotifyPropertyChanged
{
    protected void OnPropertyChanged(string porpName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(porpName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private System.Windows.Media.Brush _foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

    public string FullName
    {
        get
        {
            return "Hello world";
        }
    }

    public System.Windows.Media.Brush ForegroundColor
    {
        get { return _foregroundColor; }
        set
        {
            _foregroundColor = value;
            OnPropertyChanged("ForegroundColor");
        }
    }
}

Running app

请记住,如果您想在 VM 中为 ForegroundColor 设置新值,您应该这样做:

ForegroundColor = System.Windows.Media.Brushes.Red;

引发 PropertyChangedEvent

根据有关您的问题的新信息,您可以尝试以下解决方案:

CustomerHeaderViewModel.cs

class CustomerHeaderViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Customer> Customers { get; set; }

    public void LoadCustomers()
    {
        ObservableCollection<Customer> customers = new ObservableCollection<Customer>();

        //this is where you would actually call your service
        customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", NumberOfContracts = 23 });
        customers.Add(new Customer { FirstName = "Jane", LastName = "Smith", NumberOfContracts = 22 });
        customers.Add(new Customer { FirstName = "John", LastName = "Tester", NumberOfContracts = 33 });
        customers.Add(new Customer { FirstName = "Robert", LastName = "Smith", NumberOfContracts = 2 });
        customers.Add(new Customer { FirstName = "Hank", LastName = "Jobs", NumberOfContracts = 5 });

        Customers = customers;
    }
    protected void OnPropertyChanged(string porpName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(porpName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private System.Windows.Media.Brush _foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

    public System.Windows.Media.Brush ForegroundColor
    {
        get { return _foregroundColor; }
        set
        {
            _foregroundColor = value;
            OnPropertyChanged("ForegroundColor");
        }
    }
}

CustomerHeaderView.xaml

<UserControl x:Class="TestMvvm444.Views.CustomerHeaderView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="main">
    <Grid>
        <StackPanel HorizontalAlignment="Left">
            <ItemsControl ItemsSource="{Binding Path=Customers}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Orientation="Horizontal">
                                <TextBox
                                Text="{Binding Path=FirstName, Mode=TwoWay}" 
                                Width="100" 
                                Margin="3 5 3 5"/>
                                <TextBox 
                                Text="{Binding Path=LastName, Mode=TwoWay}" 
                                Width="100"
                                Margin="0 5 3 5"/>
                                <TextBlock 
                                Text="{Binding Path=FullName, Mode=OneWay}" 
                                Foreground="{Binding ElementName=main, Path=DataContext.ForegroundColor}"
                                Margin="0 5 3 5"/>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </Grid>
</UserControl>

在呈现的场景中,ForegroundColor 属性位于 CustomerHeaderViewModel.cs 中,因此它对所有客户都有值(value)。在 CustomerHeaderView.xaml 中,我为 UserControl 添加了 x:Name,以便可以引用此元素的 DataContext。如果你不想为 UserControl 使用 x:Name,你可以试试这个:

<TextBlock 
    Text="{Binding Path=FullName, Mode=OneWay}"
    Foreground="{Binding RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type UserControl}}, Path=DataContext.ForegroundColor}"
    Margin="0 5 3 5"/>

请记住,此控件的 DataContext 是在 MainWindow.cs 中较早设置的。

主窗口.cs

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        CustomerHeaderViewModel customerHeaderViewModel = new CustomerHeaderViewModel();
        customerHeaderViewModel.LoadCustomers();
        CustomerHeaderView.DataContext = customerHeaderViewModel;
    }
}

App

关于c# - 如何将前景绑定(bind)到我的 ViewModel 中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5601489/

相关文章:

android - 如何编写一个使用 Context 从 Android 框架中检索数据的用例

java - unity调用android java类的静态函数

c# - 需要知道如何使用 c# 在数组中搜索来在 ES 中进行搜索

c# - 为 OPEN XML 中的单元格设置 Font.Bold 和 Column.Width

c# - WPF C# : Using Tasks

c# - VisualStateGroup的ViewModel方法事件

c# - 在可重启模式下以编程方式在多个 block 中并行下载文件

c# - 尝试生成大量以 mysql 数据库内容作为源的组合框时遇到问题

WPF 编译开始因交互和交互性而失败

c# - MVVM WPF在dataGrid中实现Find和FindNext