[英]WPF binding controls
我剛剛開始學習WPF桌面應用程序。 我在下面寫了一些簡單的代碼來執行綁定操作。
問題是:我想要在TextBox中鍵入sth並在TextBlock中同時看到它,但是在編譯和運行應用程序之后,窗體上的控件無法像我所描述的那樣運行。
有人可以幫我解決嗎?
MainWindow.xaml:
<Window x:Class="Napisy.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:Napisy"
xmlns:mv="clr-namespace:Napisy.ModelWidoku"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<mv:NapisyModelWidoku x:Key="napisyModelWidoku"/>
</Window.Resources>
<Grid DataContext="{StaticResource napisyModelWidoku}">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<TextBox Grid.Row="1" Margin="10,10,10,10" Text="{Binding Path=Tekst,Mode=TwoWay}"/>
<TextBlock Grid.Row="2" Margin="10,10,10,10" Text="{Binding Path=Wyswietl,Mode=OneWay}"/>
</Grid>
</Window>
ViewModel代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Napisy.Model;
using System.ComponentModel;
namespace Napisy.ModelWidoku
{
public class NapisyModelWidoku : INotifyPropertyChanged
{
NapisyModel model = new NapisyModel();
public string Tekst
{
get
{
return model.Tekst;
}
set
{
model.Tekst = value;
OnPropertyChanged(nameof(Tekst));
OnPropertyChanged(nameof(Wyswietl));
}
}
public string Wyswietl
{
get
{
return model.Tekst;
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string nazwa)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nazwa));
}
}
}
型號代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Napisy.Model
{
public class NapisyModel
{
public string Tekst { get; set; }
}
}
編輯:
在TextBox中輸入文本后,TextBlock仍不會自動刷新。 仍然希望我收到提示。 謝謝
我運行了您的代碼,但它不起作用,因為PropertyChanged為null。 您必須設置視圖的數據上下文,以便可以綁定PropertyChangedEventHandler。
在后面添加代碼,即MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new NapisyModelWidoku();
}
除了在兩個綁定中添加UpdateSourceTrigger
,還進行以下更改,
public string Tekst
{
get
{
return model.Tekst;
}
set
{
model.Tekst = value;
OnPropertyChanged("Tekst");
OnPropertyChanged("Wyswietl");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.