为什么不显示标签内容?

时间:2018-11-15 16:51:25

标签: c# xaml mvvm label

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

ViewModelBase

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>

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

但是当我运行应用程序时,标签为空 enter image description here

出什么问题了?

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

3 个答案:

答案 0 :(得分:2)

有些框架提供的类已经实现了所需的接口,如果您想自己做,则有可能:

首先,您拥有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);
}

[EDIT]:我想保留答案的历史记录,因此请在下面用完整的函数示例检查我的编辑内容:

通常,我拆分了更多文件,但我想保持简单,因此您需要2个文件(我试图应用MVVM模式,因此要添加目录): -Views \ MainWindow.xaml -ViewModels \ MainWindowViewModel.cs

Views \ 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"> 代替

StartupUri="MainWindow.xaml">

答案 1 :(得分:1)

您是否已将窗口/控件上的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-页面设置):

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

这将显示您的期望,并正确显示余额。您可以尝试一些方法来查看问题所在:

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

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

答案 2 :(得分:0)

删除边距解决了问题。我猜是页边距推开了标签。