![](/img/trans.png)
[英]XamarinForms XAML: How can I inherit properties from another XAML file like ResourceDictionaries?
[英]In WPF, how can I inherit from ToolBar AND have a XAML file?
我可以通过创建一个普通的C#类来继承并增强ToolBar类,然后执行以下操作:
public class NiceToolBar : ToolBar
{
private ToolBarTray mainToolBarTray;
public NiceToolBar()
{
mainToolBarTray = new ToolBarTray();
mainToolBarTray.IsLocked = true;
this.Background = new SolidColorBrush(Colors.LightGray);
...
但这迫使我用如下代码操纵所有控件:
ToolBar toolBar = new ToolBar();
toolBar.Background = new SolidColorBrush(Colors.Transparent);
toolBar.Cursor = Cursors.Hand;
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
TextBlock tb = new TextBlock();
tb.Text = label;
tb.Margin = new Thickness { Top = 3, Left = 3, Bottom = 3, Right = 10 };
Image image = new Image();
image.Source = new BitmapImage(new Uri("Images/computer.png", UriKind.Relative));
sp.Children.Add(image);
sp.Children.Add(tb);
toolBar.Items.Add(sp);
我真正需要的是XAML来完成繁琐的参数分配和布局。
因此,我创建了一个新的用户控件 ,并将其后面的代码更改为继承ToolBar,如下所示:
public partial class SmartToolBar : ToolBar
{
public SmartToolBar(string label)
{
InitializeComponent();
TheLabel.Text = label;
}
}
在我的XAML中,我输入了以下内容:
<UserControl x:Class="TestUserControl.Helpers.SmartToolBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Horizontal">
<Image Source="Images/computer.png"/>
<TextBlock x:Name="TheLabel"/>
</StackPanel>
</UserControl>
但是当我运行它时,我得到了错误:
“ TestCallConstructor.Helpers.SmartToolBar”的部分声明不能定义不同的基类
如何使用 XAML进行用户控制?
如果您要从ToolBar
继承,则不会编写UserControl
,因为ToolBar
不能从UserControl
继承。 您的XAML将基本类指定为UserControl
而C#将指定ToolBar
。 显然那里存在冲突。
首先,我不理解您在代码后面做这些工作的前提。 为什么不将ToolBar
的ItemsSource
绑定到项目集合,并使用常规的ItemsControl
属性来控制渲染?
您正在寻找自定义控件(不是UserControl)。 编写自定义控件时,可以指定其默认视图(即XAML)。
您可以通过Google搜索如何在WPF中创建自定义控件,但这是我为您搜索的一个链接如何创建WPF自定义控件 。
希望这可以帮助 :)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.