【问题标题】:Why does not display the content of the label?为什么不显示标签的内容?
【发布时间】:2018-11-23 02:28:04
【问题描述】:

所以我有一个带有标签的视图,并且我有一个 ViewModel。

视图模型库

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual bool SetAndRaisePropertyChanged<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
            return false;
        storage = value;
        this.RaisePropertyChanged(propertyName);
        return true;
    }

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

ViewModel 是这样的:

  private string _balance = "1111$";
    public string Balance
    {
        get { return _balance; }
        set { SetAndRaisePropertyChanged(ref _balance, value); }
    }

这是视图:

    <UserControl x:Class="monei_project.MainUpperView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:project"
         xmlns:vm="clr-namespace:project.ViewModels"
         mc:Ignorable="d" 
         d:DesignHeight="100" d:DesignWidth="2200" FontFamily="Open Sans">
<UserControl.Resources>
    <vm:MainUpperViewModel  x:Key="MainUpperViewModel"/>
</UserControl.Resources>
<Grid DataContext="{Binding Source={StaticResource MainUpperViewModel}}">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>
    <Rectangle Grid.RowSpan="1" Grid.ColumnSpan="22" Fill="#013542"></Rectangle>
    <Label  Grid.Column="6" Grid.ColumnSpan="2" VerticalAlignment="Center" Foreground="White" FontSize="16">Balance:</Label>
    <Label x:Name="lblBalance" Grid.Column="7" Grid.ColumnSpan="5" VerticalAlignment="Center" Foreground="White" FontFamily="Open Sans SemiBold" FontSize="24" Margin="55,28,45,33">
        <Label.Content>
            <Binding Path="Balance"/>
        </Label.Content>
    </Label>
</Grid>

在设计器中,我可以看到标签的内容

但是当我运行应用程序时,标签是空的

有什么问题?

我已经创建了一些 ViewModel,但在那里我使用了文本框。我们使用了 INotifyPropertyChanged 接口,我不确定它是如何工作的,所以我的猜测是,它设置了内容,但不会显示它,因为标签没有更新,所以我尝试使用 OnPropertyChanged 函数PropertyChangedEventHandler,我们之前对其他 ViewModel 使用过的,但是也没用,不知道哪里出了问题。

【问题讨论】:

  • 您很好地理解了这个问题,并且您走在正确的道路上,请参阅我的答案以获取更多信息^^

标签: c# xaml mvvm label


【解决方案1】:

有些框架提供的类已经实现了所需的接口,如果你想自己做,这里有一种可能:

首先你有你的 ViewModelBase 并且你所有的 ViewModel 都应该继承它

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected virtual bool SetAndRaisePropertyChanged<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
            return false;
        storage = value;
        this.RaisePropertyChanged(propertyName);
        return true;
    }
}

然后在您的视图模型中,您将像这样声明您的属性:

private String _mBalance;
public String Balance
{
  get { return _mBalance; }
  set => SetAndRaisePropertyChanged(ref _mBalance, value);
}

[编辑]:我想保留答案的历史记录,因此请在下面使用完整的功能示例检查我的编辑:

通常我会拆分更多文件,但我想保持简单,所以你需要 2 个文件(我正在尝试应用 MVVM 模式,所以我正在添加目录): - 视图\MainWindow.xaml - ViewModels\MainWindowViewModel.cs

视图\MainWindow.xaml:

<Window x:Class="StackOverflow_DBG.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:StackOverflow_DBG"
        xmlns:viewmodels="clr-namespace:StackOverflow_DBG.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="400">
    <Window.DataContext>
        <viewmodels:MainWindowViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Grid.Row="1" Grid.Column="0" Content="{Binding LabelTxt}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding ValueTxt}"/>
        <Button Grid.Row="1" Grid.Column="2" Content="Change Label" Command="{Binding ChangeLabel}"/>
    </Grid>
</Window>

ViewModels\MainWindowViewModel.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace StackOverflow_DBG.ViewModels
{
    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected virtual bool SetAndRaisePropertyChanged<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
        {
            if (EqualityComparer<T>.Default.Equals(storage, value))
                return false;
            storage = value;
            this.RaisePropertyChanged(propertyName);
            return true;
        }
    }

    public class RelayCommand : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        private Action methodToExecute;
        private Func<bool> canExecuteEvaluator;
        public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)
        {
            this.methodToExecute = methodToExecute;
            this.canExecuteEvaluator = canExecuteEvaluator;
        }
        public RelayCommand(Action methodToExecute)
            : this(methodToExecute, null)
        {
        }
        public bool CanExecute(object parameter)
        {
            if (this.canExecuteEvaluator == null)
            {
                return true;
            }
            else
            {
                bool result = this.canExecuteEvaluator.Invoke();
                return result;
            }
        }
        public void Execute(object parameter)
        {
            this.methodToExecute.Invoke();
        }
    }

    class MainWindowViewModel : ViewModelBase
    {
        private String m_LabelTxt = "Foo";
        public String LabelTxt
        {
            get { return m_LabelTxt; }
            set => SetAndRaisePropertyChanged(ref m_LabelTxt, value);
        }

        private String m_ValueTxt;
        public String ValueTxt
        {
            get { return m_ValueTxt; }
            set => SetAndRaisePropertyChanged(ref m_ValueTxt, value);
        }

        private RelayCommand m_ChangeLabel;
        public RelayCommand ChangeLabel
        {
            get { return m_ChangeLabel; }
            set { m_ChangeLabel = value; }
        }

        public MainWindowViewModel()
        {
            ChangeLabel = new RelayCommand(() => {
                if (LabelTxt == "Foo")
                {
                    LabelTxt = "Bar ";
                }
                else
                {
                    LabelTxt = "Foo ";
                }
            });
        }
    }
}

通过这种方式,您还可以了解如何绑定按钮。按下按钮以查看更新是否完成。 如果使用与我相同的目录,请记住编辑 app.xaml 以使用 StartupUri="Views/MainWindow.xaml"&gt; 而不是

StartupUri="MainWindow.xaml">

【讨论】:

  • 感谢您的回答。这个 ViewModelBase 是一个非常棒的想法,我在编程时才开始这样思考。所以我用三个函数创建了你建议的 BaseViewModel。我使用了三个函数,因为我真的不明白这些函数是如何工作的。我从你的例子中得到了两个函数,我还添加了我们在这个项目中之前使用的函数。我会编辑帖子,你可以在那里看到。函数在做什么?还是行不通。我应该将哪个函数绑定到哪个 XAML 属性才能使其工作?
  • 2 个问题,您不需要 OnPropertyChanged,它已由我提供的代码处理。您修改中真正的大问题是: set { SetAndRaisePropertyChanged(ref _balance, "1111$");你真的需要保留我发布的代码。单词 value 是一个关键字,表示您为设置您的属性而提供的值。获取我的代码,然后您可以将属性设置为经典变量: Balance = "1111$";如果要使用默认值进行初始化,请在私有部分进行: private String _mBalance = String.Empty;例如
  • 对于数据上下文(您在 xaml 中设置它),您的方式可能有效,但我认为您可以做得更好。也许明天我可以根据需要分享更多代码,但试试我说的,应该没问题。
  • 还是没弄明白,怎么弄,不胜感激。
  • 添加完整示例 ;)
【解决方案2】:

您是否将窗口/控件上的 DataContext 正确设置为您的视图模型?您需要先设置 DataContext,然后才能使用绑定。因此,您可能应该使用正确的绑定方式:

<Label Content="{Binding Balance}" ... />

编辑:

好的,我会给你一个具体的例子来说明我的意思。此外,使用视图模型作为StaticResource 会遇到很多问题。我为什么这么说?因为一旦您开始向视图模型添加依赖项(访问业务逻辑等),您将需要某种形式的依赖项注入 (DI) 或类似的方式来执行此操作。

所以你有你的ViewModelBase,所以我会使用它而不是重复自己。这是一个简单的视图模型:

public class AccountViewModel : ViewModelBase
{
    string _balance = "1111$";

    public AccountViewModel(string accountNumber)
    {
        AccountNumber = accountNumber;
    }

    public string AccountNumber { get; }

    public string Balance
    {
        get { return _balance; }
        set { SetAndRaisePropertyChanged(ref _balance, value); }
    }
}

这是查看代码 (MainWindow.xaml):

<Window x:Class="testProj.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
    <Grid>
        <Label Content="{Binding Balance}" />
    </Grid>
</Window>

以及背后的代码 (MainWindow.xaml.cs):

public partial class MainWindow
{
    public MainWindow(AccountViewModel dataContext)
    {
        DataContext = dataContext;
        InitializeComponent();
    }
}

为了好玩,App.xaml.cs(为 BuildAction - Page 设置):

public partial class App
{
    [STAThread]
    public static void Main(string[] args)
    {
        new MainWindow(new AccountViewModel("123456789")).ShowDialog();
    }
}

这将显示您的预期,并正确显示余额。您可以尝试以下几件事来了解您的问题是什么:

  1. 调试时输出窗口中是否有任何信息告诉您是否发生绑定错误?

您能否提供一个显示所有部分的较短版本的应用程序(即重复问题的简短项目)并将其上传到某个地方?

【讨论】:

  • 我不知道你所说的 DataContext 是什么意思,但是我更新了 XAML 代码,你可以看到我是如何将 ViewModel 绑定到 View 的。
  • 无论如何我尝试了您的代码,但仍然无法正常工作,在我看来它正在做同样的事情。
  • 也许我不清楚。所以当我更新视图时绑定工作正常,但是当我第一次打开窗口时,它不会显示属性的初始值,就在我用更新触发它之后
  • 您是否尝试过使用 Visual Studio 中的 Live Visual Tree 资源管理器检查标签并查看其 Content 属性最初是什么?您采取了哪些调试步骤来验证 Balance 属性是否已正确初始化为您期望的值?
  • 边距是问题所在。 :)
【解决方案3】:

删除边距解决了问题。我猜边距推出了标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多