[英]How to set a custom class instance to Button.Content property via XAML markup?
In my WPF Application I created some Class1
: 在我的WPF应用程序中,我创建了一些
Class1
:
namespace WpfApplication1 {
class Class1 {
public override string ToString() {
return "Hello, WPF!";
}
}
}
Now I want to set the instance of this class to Button.Content
property in the XAML markup. 现在,我想在XAML标记
Button.Content
此类的实例设置为Button.Content
属性。 How can I do it? 我该怎么做?
I try to do it: 我尝试这样做:
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" HorizontalAlignment="Left"
Margin="246,93,0,0" VerticalAlignment="Top" Width="75">
<Button.Content>
<!-- ERROR: This is wrong syntax: -->
<Object x:Class="WpfApplication1.Class1"/>
</Button.Content>
</Button>
</Grid>
</Window>
What is right syntax for this case? 在这种情况下正确的语法是什么?
A better practice is to implement INotifyPropertyChanged
and a property which will be binded in xaml. 更好的做法是实现
INotifyPropertyChanged
和将在xaml中绑定的属性。 something like that: 像这样的东西:
class Class1 {
private string _Text;
public Class1(){
_Text = this.ToString();
}
public override string ToString() {
return "Hello, WPF!";
}
}
public string Text
{
get{return _Text;}
protected set { _Text = value;
NotifyPropertyChanged("Text");
}
}
In XAML do: 在XAML中:
<Button Content="{Binding Path=Text,UpdateSourceTrigger=PropertyChanged}"
I hope that provide a solution to your issue. 希望为您的问题提供解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.