【发布时间】:2017-02-14 15:53:33
【问题描述】:
在工作中,我有几个页面,每个页面的按钮都在相同的位置,并且具有相同的属性。每一页也有细微的差别。为此,我们创建了一个用户控件模板并将所有按钮放入其中,然后将该用户控件应用于所有页面。然而,现在访问按钮并从每个页面的 xaml 修改它们相当困难,因为它们位于页面上的 UserControl 内..... 我如何优雅地访问每个页面的按钮?
我的尝试:
目前,我们绑定到一堆依赖属性。我不喜欢这个选项,因为我有很多按钮,并且需要控制这些按钮的很多属性。结果是数百个依赖属性,当我们需要更改某些内容时,真的是一团糟。
另一种方法是使用样式。我一般喜欢这种方法,但由于这些按钮位于另一个控件中,因此很难修改它们,而且模板一次只能完全正确地处理一个按钮。
Adam Kemp 发布了关于让用户插入自己的按钮 here,这是我目前尝试实施/修改的方法。不幸的是,我无法访问 Xamarin。
虽然在代码运行时插入了模板,但模板并没有正确更新按钮。如果我在 MyButton Setter 中放置一个断点,我可以看到 value 实际上是一个空按钮,而不是我在主窗口中分配的那个。我该如何解决这个问题?
这是一些简化的代码:
我的模板 UserControl 的 xaml:
<UserControl x:Class="TemplateCode.Template"
x:Name="TemplatePage"
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"
mc:Ignorable="d"
d:DesignHeight="350"
d:DesignWidth="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Background="DarkGray">
<Grid>
<Button x:Name="_button" Width="200" Height="100" Content="Template Button"/>
</Grid>
</UserControl>
我的模板用户控件背后的代码:
using System.Windows.Controls;
namespace TemplateCode
{
public partial class Template : UserControl
{
public static Button DefaultButton;
public Template()
{
InitializeComponent();
}
public Button MyButton
{
get
{
return _button;
}
set
{
_button = value; //I get here, but value is a blank button?!
// Eventually, I'd like to do something like:
// Foreach (property in value)
// {
// If( value.property != DefaultButton.property) )
// {
// _button.property = value.property;
// }
// }
// This way users only have to update some of the properties
}
}
}
}
现在是我要使用它的应用程序:
<Window x:Class="TemplateCode.MainWindow"
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"
mc:Ignorable="d"
xmlns:templateCode="clr-namespace:TemplateCode"
Title="MainWindow"
Height="350"
Width="525"
Background="LimeGreen"
DataContext="{Binding RelativeSource={RelativeSource Self}}" >
<Grid>
<templateCode:Template>
<templateCode:Template.MyButton>
<Button Background="Yellow"
Content="Actual Button"
Width="200"
Height="100"/>
</templateCode:Template.MyButton>
</templateCode:Template>
</Grid>
</Window>
现在是背后的代码:
Using System.Windows;
Namespace TemplateCode
{
Public partial class MainWindow : Window
{
Public MainWindow()
{
InitializeComponent();
}
}
}
编辑:虽然我想删除 template userControl 中不必要的依赖属性,但我仍然想在 button 上设置绑定来自 XAML 的属性。
【问题讨论】:
-
您也可以创建一个 ObservableCollection
并将其注册为 DependencyProperty。然后使用索引器访问它。否则,尝试使用样式的解决方案,stackoverflow.com/questions/40015997/… -
“因为这些按钮在另一个控件中,所以很难修改它们”:你能澄清一下吗?每个按钮一个 Style 属性,消费者拥有完全控制权。如果您想共享样式,同时为每个按钮使用不同的模板,您也可以为每个按钮设置一个模板属性。或者只是大量使用 Style.BasedOn。
标签: c# wpf xaml user-controls nested-attributes