【问题标题】:WPF TextBlock Binding to a StringWPF TextBlock 绑定到字符串
【发布时间】:2015-03-26 22:29:18
【问题描述】:

我想将 TextBlock 绑定到从 txt 文件中获取其值的字符串。字符串已正确填充,但其内容未显示。

类文件:

public partial class JokesMessageBox : Window
    {
        public JokesMessageBox()
        {
            InitializeComponent();
        }

        public string Joke { get; set; }
        public string path = "data/jokes.txt";

        public void ReadFile(string path)
        {
            Joke = File.ReadAllText(path);
        }
    }

XAML:

<TextBlock HorizontalAlignment="Left" Margin="22,10,0,0"
 TextWrapping="Wrap" Text="{Binding Joke}" VerticalAlignment="Top"
 Height="60" Width="309"/>

编辑:

在 MainWindow 类中:

 private void btnJokesFirstScreen_Click_1(object sender, RoutedEventArgs e)
        {
  JokesMessageBox jkb = new JokesMessageBox();
                jkb.Show();
                jkb.ReadFile("data/jokes.txt");
        }

我在 google、youtube、MSDN、StackOverflow 上花了 3 个多小时,但仍然无法正常工作。我错过了什么?

【问题讨论】:

  • 如何/何时调用ReadFile
  • 在构造函数中调用readfile
  • 我会推荐你​​阅读一些关于DataBinding的内容。
  • 我添加了调用 ReadFile() 的位置。

标签: c# wpf xaml


【解决方案1】:

如果您需要更新绑定,属性Joke 必须是DependencyPropertyWindows 必须实现INotifyPropertyChanged 接口。

在视图上,绑定需要知道Source

示例 #1(使用 DependencyProperty):

public partial class JokesMessageBox : Window
{
    public JokesMessageBox()
    {
        InitializeComponent();

        ReadFile(Path); //example call
    }

    public string Joke
    {
        get { return (string)GetValue(JokeProperty); }
        set { SetValue(JokeProperty, value); }
    }

    public static readonly DependencyProperty JokeProperty =
        DependencyProperty.Register("Joke", typeof(string), typeof(JokesMessageBox), new PropertyMetadata(null));


    public const string Path = "data/jokes.txt";

    public void ReadFile(string path)
    {
        Joke = File.ReadAllText(path);
    }
}

示例#2(使用INotifyPropertyChanged接口):

public partial class JokesMessageBox : Window, INotifyPropertyChanged
{
    public JokesMessageBox()
    {
        InitializeComponent();

        ReadFile(Path); //example call
    }

    private string _joke;

    public string Joke
    {
        get { return _joke; }
        set
        {
            if (string.Equals(value, _joke))
                return;
            _joke = value;
            OnPropertyChanged("Joke");
        }
    }

    public const string Path = "data/jokes.txt";

    public void ReadFile(string path)
    {
        Joke = File.ReadAllText(path);
    }


    //INotifyPropertyChanged members
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

以及视图(XAML 部分):

...
<TextBlock HorizontalAlignment="Left" Margin="22,10,0,0"
    TextWrapping="Wrap" 
    Text="{Binding Joke,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window}}" 
    VerticalAlignment="Top"
    Height="60" Width="309"/>
...

希望对你有帮助。

【讨论】:

  • 这成功了!我去了第二个例子。在我读完这篇文章后:link 我认为这将是一件又快又容易的事情。现在我查看了其他人发布的其他类似问题,我注意到了这个 INotifyPropertyChanged 接口。我会调查的。谢谢!
【解决方案2】:

当您读取文件的内容时,您将读取的字符串分配给您的Joke 属性:

Joke = File.ReadAllText(path);

TextBlockText property 确实绑定到该属性(如果您已正确设置data context):

Text="{Binding Joke}"

但是,缺少的是绑定不可能知道属性值已更改。您需要发出通知关于属性更改。

有两种方法可以被 WPF 绑定识别:

【讨论】:

    【解决方案3】:

    你的类没有实现 INotifyPropertyChanged 接口。因此,当您更改属性时,Joke TextBlock 不会更新。我会这样做:

    public partial class JokesMessageBox : Window, INotifyPropertyChanged
        {
            public JokesMessageBox()
            {
                InitializeComponent();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            public string Joke { get; set; }
            public string path = "data/jokes.txt";
    
            public void ReadFile(string path)
            {
                Joke = File.ReadAllText(path);
                OnPropertyChanged("Joke");
            }
    
            private void OnPropertyChanged(string propertyName)
            {
                var handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }
    

    我还建议您阅读MVVM patern

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2011-10-20
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多