Silverlight 4,传递风格来控制用户内部控制

时间:2011-03-14 09:21:41

标签: xaml silverlight-4.0 code-behind

我创建了一个UserControl,其中包含一个AutoCompleteBox来简化绑定。现在需求已经改变,我需要将样式传递给AutoCompleteBox。我为我的UserControl添加了样式的DependencyProperty。绑定有效,但未应用样式。

这是我背后的代码:

public partial class CustomAutoCompleteBox
{
    public static readonly DependencyProperty ContentStyleProperty = DependencyProperty.Register(
                "ContentStyle",
                typeof(Style),
                typeof(CustomAutoCompleteBox),
                new PropertyMetadata(OnContentStyleChanged));

/// <summary>
/// Initializes a new instance of the <see cref="CustomAutoCompleteBox"/> class.
/// </summary>
public CustomAutoCompleteBox()
{
    this.InitializeComponent();
}

/// <summary>
/// Gets or sets ContentStyle.
/// </summary>
public Style ContentStyle
{
    get
    {
        return (Style)this.GetValue(ContentStyleProperty);
    }

    set
    {
        this.SetValue(ContentStyleProperty, value);
    }
}

private static void OnContentStyleChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var customAutoCompleteBox = obj as CustomAutoCompleteBox;
    var newValue = e.NewValue as Style;
    if (customAutoCompleteBox != null && newValue != null)
    {
        customAutoCompleteBox.ContentStyle = newValue;
    }
}

和xaml:

<Grid x:Name="LayoutRoot">
<Input:AutoCompleteBox Style="{Binding ContentStyle}"
                       MinimumPrefixLength="0"
                       ItemTemplate="{StaticResource DescriptionItemTemplate}"
                       ValueMemberBinding="{Binding Description, Mode=TwoWay}"
                       SelectedItem="{Binding Value, ValidatesOnDataErrors=True, Mode=TwoWay}"
                       ItemsSource="{Binding Values}"
                       Text="{Binding Text, Mode=TwoWay}"
                       Behaviors:AutoCompleteBoxBehaviors.PopulatingCommand="{Binding PopulationCommand}"
                       Behaviors:AutoCompleteBoxBehaviors.ItemFilterPredicate="{Binding ItemFilterPredicate}"/>

</Grid>

我希望有人可以指出我做错了什么。

干杯 AC

1 个答案:

答案 0 :(得分:1)

上面的代码将依赖项属性添加到名为ContentStyle的自定义控件中。但是,您在那里的XAML将尝试将控件的Style绑定到名为“ContentStyle”的DataContext上的值。这是两件不同的事情。

您想要的是能够以编程方式为控件分配新样式。不幸的是,这只能进行一次,因为一旦设置了样式就无法“取消设置”。这是来自Silverlight论坛。

http://forums.silverlight.net/forums/p/11670/37375.aspx

但是,可以设置一次样式,因此解决此问题的最简单方法是在帖子中建议的。以编程方式从控制树中删除自定义控件,设置新样式,然后将其添加回父控件。