【问题标题】:Binding nested control property to Page将嵌套控件属性绑定到 Page
【发布时间】:2015-06-23 23:07:48
【问题描述】:
<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 的属性。我该怎么做?

谢谢。

【问题讨论】:

    标签: c# wpf windows


    【解决方案1】:

    从 xaml 中删除 Source 属性。 您可以选择添加 FallbackValue

    <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
    
    // ...
    

    话虽如此,我建议学习模型-视图-视图模型模式,该模式有助于将 GUI 代码与数据源分开。搜索mvvm in wpf

    【讨论】:

    猜你喜欢
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2012-07-19
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多