我有一个名为Tile的自定义控件,其中包含一个边框。 我希望能够在我的MainPage.xaml中更改Tile的边框背景颜色,我添加了控件:
以下是我的tile类的代码:
public static readonly DependencyProperty MyDpProperty = DependencyProperty.Register
("TileColor",
typeof(SolidColorBrush),
typeof(Tile),
new PropertyMetadata(default(SolidColorBrush)));
public SolidColorBrush TileColor
{
get
{
return (SolidColorBrush)this.GetValue(MyDpProperty);
}
set
{
this.SetValue(MyDpProperty, value);
}
}
这是我的Tile CustomControl中的xaml:
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<Border Background="{Binding TileColor}"></Border>
</Grid>
这是我的MainPage.xaml:
<local:Tile Grid.Column="5">
<local:Tile.TileColor>
<SolidColorBrush Color="Beige"></SolidColorBrush>
</local:Tile.TileColor>
</local:Tile>
显示图块,但颜色不会设置.. 能不能指出我哪里错了?
答案 0 :(得分:-1)
您需要将DependencyProperty
重命名为TileColorProperty
(如@dkozl所说),您还需要在控件中使用{TemplateBinding}
:
<强>主题\ generic.xaml 强>
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:local="clr-namespace:Silverlight80App">
<Style TargetType="local:Tile">
<Setter Property="TileColor" Value="Aquamarine"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:Tile">
<Rectangle Fill="{TemplateBinding TileColor}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
<强> Tile.cs 强>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Silverlight80App
{
class Tile : ContentControl
{
public static readonly DependencyProperty TileColorProperty =
DependencyProperty.Register("TileColor", typeof(Brush), typeof(Tile),
null);
public Brush TileColor
{
get { return (Brush)GetValue(TileColorProperty); }
set { SetValue(TileColorProperty, value); }
}
public Tile()
{
DefaultStyleKey = typeof(Tile);
}
}
}
<强>用法强>
<StackPanel xmlns:local="clr-namespace:Silverlight80App">
<local:Tile HorizontalAlignment="Stretch" Height="10" />
<local:Tile HorizontalAlignment="Stretch" Height="10" TileColor="Red"/>
</StackPanel>