簡體   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