我要找的示例代碼簡潔片斷,做以下設置組件用戶控件的屬性:如何在WPF XAML
從更高的層次UserControl
,我想改變一個對象的屬性(比如說)經由XAML在子UserControl
內。
例如,假設我有一個UserControl
,名爲Widget
,其中包含Grid
的Button
s。每個Button
都有不同的背景和邊框顏色。然後我想要一個名爲WidgetPanel
的UserControl
,它保留Grid
的Widgets
。
對於WidgetPanel
內的每個Widget
定義,我想是能夠設置BorderBrush
和每個單獨的按鈕(命名button0
,button1
,button2
分別)通過XAML屬性的Background
。我還想以編程方式在WidgetPanel.xaml.cs
後面的代碼中更改事件的這些值。
這裏是XAML和後面爲每個對象的代碼:
XAML爲Widget
<UserControl x:Class="WpfApp1.Widget"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button BorderBrush="Black" BorderThickness="4" Background="#FF249AA6" Grid.Row="0"/>
<Button BorderBrush="Blue" BorderThickness="4" Background="#FFFF0046" Grid.Row="1"/>
<Button BorderBrush="Orange" BorderThickness="4" Background="Blue" Grid.Row="2"/>
</Grid>
</UserControl>
代碼後面爲Widget
using System.Windows.Controls;
namespace WpfApp1
{
public partial class Widget : UserControl
{
public Widget()
{
InitializeComponent();
}
}
}
XAML爲WidgetPanel
:
<UserControl x:Class="WpfApp1.WidgetPanel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<local:Widget Grid.Column="0"/>
<local:Widget Grid.Column="1"/>
</Grid>
</UserControl>
背後
代碼WidgetPanel
:
using System.Windows.Controls;
namespace WpfApp1
{
public partial class WidgetPanel : UserControl
{
public WidgetPanel()
{
InitializeComponent();
}
}
}
在'WidgetPanel'和'Widget'中定義了一些屬性。 –
如果你可以提供一個答案,那麼我將會非常感激。 –
小部件中的按鈕列表是否已預定義?如果是的話,你可以在'Widget'類(像FirstButtonBorderBrush和FirstButtonBackground)中創建所需的依賴屬性,並按照@LeiYang的說法將按鈕的屬性綁定到它們。 – Maxim