【问题标题】:Silverlight 4, pass style to control inside user controlSilverlight 4,通过样式控制内部用户控件
【发布时间】:2011-03-15 01:15:01
【问题描述】:

我创建了一个包含 AutoCompleteBox 的 UserControl 来简化绑定。现在要求发生了变化,我需要将样式传递给 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>

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

干杯 交流

【问题讨论】:

    标签: xaml silverlight-4.0 code-behind


    【解决方案1】:

    您上面的代码将一个依赖属性添加到您的名为ContentStyle 的自定义控件中。但是,您在那里的 XAML 会尝试将控件的样式绑定到 DataContext 上名为“ContentStyle”的值。这是两个不同的东西。

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多