繁体   English   中英

使用 ViewModels 通过按钮将文本框绑定到文本块

[英]Binding Textbox to Textblock via a Button, using ViewModels

我正在尝试了解 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呢?

您的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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM