正在将嵌套控件属性绑定到页面
本文关键字:绑定 属性 控件 嵌套 | 更新日期: 2023-09-27 17:59:22
<Page x:Name="ChatPageName" x:Class="WindowsDesktop.Chat.ChatPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WindowsDesktop.Chat"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="ChatPage">
<Grid>
<ToolBar x:Name="ToBar" Grid.Row="0" HorizontalAlignment="Left" Margin="10,42,0,0" VerticalAlignment="Top" Height="28" Width="280">
<TextBox x:Name="ToBarTextBox" Height="22.6666666666667" Margin="0" TextWrapping="Wrap" Text="{Binding Path=ToBarText, Source=ChatPageName}" VerticalAlignment="Top" Width="120"/>
<Button x:Name="AddContactButton" Content="Add" Height="23" VerticalAlignment="Top" Width="75" Margin="0,0,0,-0.333" Click="AddContactButton_Click"/>
</ToolBar>
我正在尝试将ToBarTextBox上的文本绑定到我的类ChatPage上名为ToBarText的属性。我该怎么做?
谢谢。
从xaml中删除Source属性可选地,您可以添加回退值
<TextBox x:Name="ToBarTextBox" Height="22.6666666666667" Margin="0" TextWrapping="Wrap" Text="{Binding Path=ToBarText, FallbackValue=ToBarText}" VerticalAlignment="Top" Width="120"/>
在后面的代码中,您需要设置DataContext(它负责为绑定选择数据源(。在当前的设置中,您似乎使用了一个类来处理GUI和提供数据。在这种情况下,使用:
public ChatPage()
{
// constructor code
this.DataContext = this;
}
您还需要设置数据源以实现INotifyPropertyChanged
:
internal class ChatPage : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
// ...
话虽如此,我建议您学习Model-View-ViewModel模式,它有助于将GUI代码与数据源分离。搜索mvvm in wpf