DependencyProperty и UserControl в WPF

Я создал UserControl с меткой и прямоугольником внутри 2 строк сетки. Я добавил свойство

public string SetText
{
    get
    {
        return (string)GetValue(mLabel.ContentProperty);
    }
    set
    {
        SetValue(mLabel.ContentProperty, value);
    }
}

Использование имущества

<local:PlayerMiniImage SetText="Player 1" ...

Когда я использовал это свойство, шрифт метки изменился, а прямоугольник исчез. Есть идеи?


person Phox    schedule 23.12.2011    source источник
comment
Как SetText связан в PlayerMiniImage?   -  person Louis Kottmann    schedule 23.12.2011


Ответы (1)


Если вы определяете UserControl...

<UserControl x:Class="...">
    <Border>
        <!-- ... -->
    </Border>
</UserControl>

Затем все внутри него, здесь Border, является Content, поэтому, если вы установите ContentProperty, все будет заменено.


Чтобы установить содержимое метки, создайте новый DP:

public static readonly DependencyProperty LabelContentProperty =
    DependencyProperty.Register("LabelContent", typeof(object), typeof(MyUserControl), new UIPropertyMetadata(null));
public object LabelContent
{
    get { return (object)GetValue(LabelContentProperty); }
    set { SetValue(LabelContentProperty, value); }
}

и привяжите к нему метку:

<Label Content="{Binding LabelContent, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
person H.B.    schedule 23.12.2011