我正在寻找一个简洁的示例代码片段,它执行以下操作:
从更高级SELECT *
FROM messages
WHERE post_user_id = 10 or msg_user_id = 10
ORDER BY msg_date DESC
开始,我想通过XAML更改子UserControl
中对象的属性(比如Button
)。
例如,假设我有一个名为UserControl
的{{1}},其UserControl
个Widget
。每个Grid
都有不同的背景和边框颜色。然后,我想要一个名为Button
的{{1}}来维持Button
UserControl
。
对于WidgetPanel
中的每个Grid
定义,我希望能够设置每个按钮的Widgets
和Widget
(名为WidgetPanel
,BorderBrush
,Background
分别通过XAML属性。我还想以编程方式更改button0
中隐藏的代码中的事件值。
这是XAML和每个对象背后的代码:
button1
button2
WidgetPanel.xaml.cs
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>
的XAML:
Widget
using System.Windows.Controls;
namespace WpfApp1
{
public partial class Widget : UserControl
{
public Widget()
{
InitializeComponent();
}
}
}
后面的代码:
WidgetPanel
答案 0 :(得分: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
}
在Widget
的XAML中:
<Button BorderBrush="{Binding Path=FirstButtonBorderBrush, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
在WidgetPanel
的XAML中:
<local:Widget x:Name="firstWidget"
FirstButtonBorderBrush="Red"/>
当然,您可以从WidgetPanel
:
firstWidget.FirstButtonBorderBrush = new SolidColorBrush(Colors.Red);
答案 1 :(得分:0)
我不确定以下想法是否有效。请尝试以下代码,它可能会解决您的疑问。
在WidgetPanel.xaml.cs中的WidgetPanel UserControl中加载Grid的Focused事件,如下所示,
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.
}
我刚刚分享了我的意见。我没有检查上面的代码。可以帮到你。