Я шукаю стислий фрагмент коду прикладу, який робить наступне:
З вищого рівня UserControl
, Я хотів би змінити властивість об'єкта (скажімо, a Button
) у межах підп UserControl
через XAML.
Наприклад, скажіть, у мене є UserControl
називається Widget
що містить Grid
від Button
s. Кожен Button
має інший колір тла та кольору рамки. Тоді я хочу мати UserControl
називається WidgetPanel
що підтримує a Grid
від Widgets
.
Для кожного Widget
визначення в межах WidgetPanel
, Я хотів би мати можливість встановити BorderBrush
і Background
кожної окремої кнопки (названа button0
, button1
, button2
відповідно) властивість через XAML. Я також хотів би програматично змінити ці значення для подій з коду позаду в 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();
}
}
}
Відповіді:
1 для відповіді № 1В Widget
клас визначає набір властивостей, що впливає на стиль внутрішніх кнопок. Наприклад, для BorderBrush
:
public partial class Widget : UserControl
{
public Widget()
{
InitializeComponent();
}
// BorderBrush for first button
public static readonly DependencyProperty FirstButtonBorderBrushProperty =
DependencyProperty.Register("FirstButtonBorderBrush",
typeof(Brush),
typeof(Widget));
public Brush FirstButtonBorderBrush
{
get { return (Brush)GetValue(FirstButtonBorderBrushProperty); }
set { SetValue(FirstButtonBorderBrushProperty, value); }
}
// ... repeat for other buttons
}
У XAML оф Widget
:
<Button BorderBrush="{Binding Path=FirstButtonBorderBrush, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
У XAML оф WidgetPanel
:
<local:Widget x:Name="firstWidget"
FirstButtonBorderBrush="Red"/>
Звичайно, ви можете встановити цю властивість з коду позаду WidgetPanel
:
firstWidget.FirstButtonBorderBrush = new SolidColorBrush(Colors.Red);
0 для відповіді № 2
Я не впевнений, чи працює ідея нижче. Спробуйте наведений нижче код, і він може вирішити ваш запит.
Підключіть фокусовану подію Grid, завантажену всередині WidgetPanel UserControl в WidgetPanel.xaml.cs, як показано нижче,
grid.Focused += Grid_Focused; //where grid is the name of Grid loaded inside a WidgetPanel user control.
private void Grid_Focused(object sender, EventArgs e)
{
Grid grid = sender as Grid;
//here you can get the children of grid i.e, you can get the usercontrols in Widget.xaml
//From the user control get its children. So you can easily get the buttons here and change the respective properties.
}
Я щойно поділився своєю думкою. Я не перевіряв вищевказаний код. Нехай вам це допоможе.