gpt4 book ai didi

c# - WPF TextBlock 绑定(bind)到字符串

转载 作者:行者123 更新时间:2023-12-05 00:50:08 29 4
gpt4 key购买 nike

我想将 TextBlock 绑定(bind)到从 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 个多小时,但仍然无法正常工作。我错过了什么?

最佳答案

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

在 View 上,绑定(bind)需要知道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接口(interface)):

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));
}
}

以及 View (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"/>
...

希望对你有帮助。

关于c# - WPF TextBlock 绑定(bind)到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29290057/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com