Windows Phone - 使用dependendy属性绑定solidcolorbrush属性

时间:2015-05-03 19:16:11

标签: c# xaml windows-phone-8 dependency-properties

我有一个名为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>

显示图块,但颜色不会设置.. 能不能指出我哪里错了?

1 个答案:

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