簡體   English   中英

使用XAML更改UserControl屬性

[英]Change UserControl property using XAML

我有我的UserControl

<UserControl x:Class="CustomCtrl.MyButton">
   <Button x:Name="Btn" />
</UserControl>

我在Window使用UserControl

<Window>
    <Grid>
        <MyButton Background="Aqua" />
    </Grid>
</Window>

我想改變Background的按鈕的屬性Btn使用屬性Background我的UserControl 與XAML。

我嘗試添加Background屬性

public class MyButton: UserControl
{
    public new Brush Background
    {
        get
        { return Btn.GetValue(BackgroundProperty) as Brush; }

        set
        { Btn.SetValue(BackgroundProperty, value); }
    }        
}

但這沒有效果。
相反,如果我使用代碼MyButtonControl.Background = Brushes.Aqua; , 有用。
為什么? 我該如何解決這個問題?

UserControl.Background UserControls不自定義控件,你必須在此屬性為如何使用沒有控制權。 如果只想更改一個控件的背景,則可以公開一個新的依賴項屬性,並將其綁定到Button.Background

在我看來,您有兩種選擇:

  1. 簡單的方法是,只需將“ Btn”背景設置為“透明”,如下所示:

     <UserControl x:Class="CustomCtrl.MyButton"> <Button x:Name="Btn" Background="Transparent"/> </UserControl> 
  2. 另一種方法是將按鈕的背景色綁定到控件的背景色:

     <UserControl x:Class="CustomCtrl.MyButton" x:Name="control"> <Button x:Name="Btn" Background="{Binding Background, ElementName=control}"/> </UserControl> 

兩者都經過測試,似乎可以正常工作。

<Window>
    <Grid>
        <MyButton Background="Aqua" />
    </Grid>
</Window>

您正在設置UserControl的背景色。 要設置Button的背景色,您必須

<UserControl x:Class="CustomCtrl.MyButton">
   <Button x:Name="Btn" Background="Aqua" />
</UserControl>

編輯(在OP注釋之后):您不能修改UserControl.Background ,但是可以使用新屬性:

public Brush ButtonBackground {
    get {
        return this.Btn.Background;
    }
    set {
        this.Btn.Background = value;
    }
}

接着:

<Window>
    <Grid>
        <MyButton ButtonBackground="Aqua" />
    </Grid>
</Window>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM