[英]How to set a custom class instance to Button.Content property via XAML markup?
在我的WPF应用程序中,我创建了一些Class1
:
namespace WpfApplication1 {
class Class1 {
public override string ToString() {
return "Hello, WPF!";
}
}
}
现在,我想在XAML标记Button.Content
此类的实例设置为Button.Content
属性。 我该怎么做?
我尝试这样做:
<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>
在这种情况下正确的语法是什么?
更好的做法是实现INotifyPropertyChanged
和将在xaml中绑定的属性。 像这样的东西:
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");
}
}
在XAML中:
<Button Content="{Binding Path=Text,UpdateSourceTrigger=PropertyChanged}"
希望为您的问题提供解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.