我已經深入研究了 WPF 和 Binding 的神奇和奧秘。一切順利,然后我撞到了磚墻,需要向比我聰明得多的人尋求幫助。
我把它剪回了一個簡單的應用程式,洗掉了我代碼中的所有其他專案。UI 有一個文本框和一個標簽。當文本框中的文本更改時,我想更新標簽。某處我錯過了一個鏈接,我想這是系結,因為我似乎從未進入過這個場景。這是代碼
主視窗.xaml.cs
using System.ComponentModel;
using System.Windows;
namespace Databinding3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string myBindedVal = "....";
public MainWindow()
{
InitializeComponent();
}
//Create properties for our variable _myBindedVal
public string MyBindedVal
{
get => myBindedVal;
set
{
NotifyPropertyChanged(nameof(MyBindedVal));
myBindedVal = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (propertyName != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
主視窗.xml
<Window x:Class="Databinding3.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:Databinding3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBox x:Name="txtbx_name" Text="Textbox" HorizontalAlignment="Center" Height="57" TextWrapping="Wrap" VerticalAlignment="Center" Width="594"/>
<Label Content="{Binding MyBindedVal, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" HorizontalAlignment="Center" Height="44" Grid.Row="1" VerticalAlignment="Center" Width="594"/>
</Grid>
</Window>
謝謝你的幫助
uj5u.com熱心網友回復:
您沒有系結 TextBox 的 Text 屬性。它應該如下所示,其中 UpdateSourceTrigger 確保在您輸入文本框時立即更新源屬性。
<TextBox Text="{Binding MyBoundVal, UpdateSourceTrigger=PropertyChanged}" .../>
上面的 Binding 沒有明確指定源物件,因此使用 Window 的 DataContext 作為源。像這樣設定 DataContext:
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
標簽系結然后就是
<Label Content="{Binding MyBoundVal}" .../>
請注意,您通常會使用 TextBlock 而不是 Label 來顯示文本:
<TextBlock Text="{Binding MyBoundVal}" .../>
屬性設定器中的執行順序也很重要。在觸發 PropertyChanged 事件之前分配支持欄位值。
public string MyBoundVal
{
get => myBoundVal;
set
{
myBoundVal = value;
NotifyPropertyChanged(nameof(MyBoundVal));
}
}
最后,NotifyPropertyChanged 方法應如下所示。測驗propertyName引數毫無意義,但您應該測驗PropertyChanged事件是否為空,通常使用空傳播運算子?.:
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351757.html
下一篇:子選單彈出背景要透明
