先贴一下我的代码,先是XAML部分,我自定义了一个Button
<Button x:Name="ButtonControl" VerticalAlignment="Top" HorizontalAlignment="Center" Width="300" Height="200" >
<Button.Template>
<ControlTemplate>
<Grid>
<Ellipse Width="{TemplateBinding Button.Width}" Height="{TemplateBinding Button.Height}" Stroke="Black">
<Ellipse.Fill>
<SolidColorBrush x:Name="EllipseBrush"/>
</Ellipse.Fill>
</Ellipse>
<TextBlock Margin="5,0,0,0" FontSize="50" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{TemplateBinding Button.Content}"></TextBlock>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
<!--<ContentPresenter.ContentTemplate>
<DataTemplate>
</DataTemplate>
</ContentPresenter.ContentTemplate>-->
</ContentPresenter>
</Grid>
</ControlTemplate>
</Button.Template>
<!--这样绑定可以正常显示数据-->
<!--<Button.Content>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="Red" Height="10" Width="10" ></Rectangle>
<TextBlock Margin="2,0,0,0" Text="{x:Bind Path=TextContent}" Foreground="Black" />
</StackPanel>
</Button.Content>-->
<Button.ContentTemplate>
<!--这样绑定不能显示数据-->
<DataTemplate x:DataType="local:MainPage">
<StackPanel Orientation="Horizontal">
<Rectangle Fill="Red" Height="10" Width="10" ></Rectangle>
<TextBlock Margin="2,0,0,0" Text="{x:Bind Path=TextContent,Mode=OneWay}" Foreground="Black"/>
</StackPanel>
</DataTemplate>
</Button.ContentTemplate>
</Button>
接下来是代码部分,我使用的是C++/CX开发
public ref class MainPage sealed
{
public:
MainPage();
property Platform::String^ TextContent
{
Platform::String^ get() { return _ContentText; }
void set(Platform::String^ value) { _ContentText = value; }
}
private:
Platform::String^ _ContentText;
};
MainPage::MainPage()
{
InitializeComponent();
TextContent = L"Hello XAML World!";
}
直接在Button的Content中绑定内容可以正常显示, 但是放在了ContentTemplate中做数据绑定就无法正常显示了?
同样的如果放在ContentPresenter.ContentTemplate 的DatatTemplate (按我的理解这个和直接放在ContentTemplate中是一样的处理)中也是无法正常显示的。
这是为什么呢?