2017-02-25 59 views
0

在我的WPF应用程序我创造了一些Class1如何通过XAML标记将自定义类实例设置为Button.Content属性?

namespace WpfApplication1 { 

    class Class1 { 
     public override string ToString() { 
      return "Hello, WPF!"; 
     } 
    } 
} 

现在我想这个类的实例设置为Button.Content属性在XAML标记。我该怎么做?

我尝试这样做:

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

什么是正确的语法对于这种情况?

+0

Class1必须公开 – levent

+0

@levent:不,它的工作原理没有'public'。 –

回答

0

这就是我所做的工作。

<Button x:Name="button" HorizontalAlignment="Left" 
     Margin="246,93,0,0" VerticalAlignment="Top" Width="75"> 
    <local:Class1 /> 
</Button> 

enter image description here

0

一个更好的做法是实现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}" 

我希望提供一个解决您的问题。

相关问题