【问题标题】:Binding Textbox to Textblock via a Button, using ViewModels使用 ViewModels 通过按钮将文本框绑定到文本块
【发布时间】:2018-04-14 04:01:47
【问题描述】:

我正在尝试了解 MVVM 的基础知识。

现在我有一个基本的 UWP 应用程序,我想在 TextBox 中输入文本,然后在按下 Button 后在 TextBlock 中显示该文本。

如何使用 MVVM 来做到这一点?

XAML

<Page.DataContext>
    <vm:MainPageViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel>
    <TextBox Width="200" Height="40" Text="{Binding FirstName, Mode=TwoWay}" ></TextBox>
    <Button  Content="Add" Click="{x:Bind ViewModel.Add}" ></Button>
    <TextBlock FontSize="30" Text="{Binding OutPut}" ></TextBlock>
</StackPanel>

MainPageViewModel:(C#)

public class MainPageViewModel : ViewModelBase
{
    public MainPageViewModel()
    {

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _OutPut;
    public string OutPut
    {
        get
        {
            return _OutPut;
        }
        set
        {
            _OutPut = value;
            RaisePropertyChanged(nameof(OutPut));
        }
    }

    private string _FirstName;
    public string FirstName
    {
        get
        {
            return _FirstName;
        }
        set
        {
            _FirstName = value;
            RaisePropertyChanged(nameof(FirstName));
        }
    }


    public void Add()
    { 
        OutPut = FirstName;
        // Debug.WriteLine(Output);
    }
}

当我按下按钮时,输入文本显示在输出窗口中,但我怎样才能让它显示在Textblock中?

【问题讨论】:

标签: c# .net mvvm binding uwp


【解决方案1】:

您的MainPageViewModelViewModelBase 必须实现INotifyPropertyChanged。仅仅添加PropertyChangedEventHandler 是不够的。

public class MainPageViewModel : ViewModelBase, INotifyPropertyChanged

public class ViewModelBase : INotifyPropertyChanged

没有INotifyPropertyChanged,您提供的代码(我在控件周围添加了StackPanel,因为页面只能有1 个内容元素)在我的机器上不起作用,在代码中添加INotifyPropertyChanged,它可以工作。


奖励:如果您想对所有绑定使用x:Bind,则必须在TextBlock 绑定上设置Mode=OneWay,因为x:Bind 的默认值是OneTime

<Page.DataContext>
    <local:MainViewModel x:Name="ViewModel" />
</Page.DataContext>

<StackPanel>
    <TextBox Width="200" Height="40" Text="{x:Bind ViewModel.FirstName, Mode=TwoWay}" ></TextBox>
    <Button  Content="Add" Click="{x:Bind ViewModel.Add}" ></Button>
    <TextBlock FontSize="30" Text="{x:Bind ViewModel.OutPut, Mode=OneWay}" ></TextBlock>
</StackPanel>

【讨论】:

  • 刚刚有一个简短的问题要问您。当我使用 Template 10 Nuget 时,我在 MainPageViewModel 中扩展了 ViewModelBase,它扩展了 BindableBase,它再次实现了 INotifyPropertyChanged。为什么我需要再次实现 INotifyPropertyChanged,而它是实现了该接口的类的子类?
  • 您正在重新定义事件处理程序,因此将其隐藏在 BindableBase(多态性)中。如果您使用的是 Template10,则应该在属性设置器中使用 Set method
猜你喜欢
  • 2016-09-09
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 2021-11-29
  • 2021-12-18
  • 2023-03-06
  • 2014-05-21
相关资源
最近更新 更多