【问题标题】:How to add a Property/Attribute to UserControl with no Code behind?如何在没有代码的情况下向 UserControl 添加属性/属性?
【发布时间】:2013-09-25 10:19:46
【问题描述】:

首先,是否可以在没有代码的情况下向 WPF UserControl 添加属性?

如果没有,假设我有一个这样的自定义 UserControl:

<UserControl x:Class="Example.Views.View"
         xmlns:vm ="clr-Example.ViewModels"
         xmlns:view ="clr-Example.Views"
         ... >
   <UserControl.DataContext>
     <vm:ViewModel/>
   </UserControl.DataContext>

   <Button Background="Transparent" Command="{Binding ClickAction}">
     <Grid>
        ...
        <Label Content="{Binding Description}"/>
     </Grid>
   </Button>
</UserControl>

有了这样的 ViewModel

public class ViewModel : INotifyPropertyChanged
{

    private ICommand _clickAction;
    public ICommand ClickAction
    {
        get { return _clickAction; }
        set
        {
            if (_clickAction != value)
            {
                _clickAction = value;
                RaisePropertyChanged("ClickAction");
            };
        }
    }

    private int _description;
    public int Description
    {
        get { return _description; }
        set
        {
            if (_description!= value)
            {
                _description = value;
                RaisePropertyChanged("Description");
            };
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        // take a copy to prevent thread issues
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
 }

我希望能够像这样设置动作:

...
<UserControl.Resources>
    <ResourceDictionary>
        <command:ButtonGotClicked x:Key="gotClicked" />
    </ResourceDictionary>
</UserControl.Resources>
<Grid>
    <view:FuelDispenserView  ClickAction="{StaticResource gotClicked}"/>
</Grid> ...

没有代码。

目前我使用这个丑陋的代码来实现我的目标,但我不喜欢它。

public partial class View : UserControl
{
    public View()
    {
        InitializeComponent();
    }
    public ICommand ClickAction {
        get {
            return ((ViewModel)(this.DataContext)).ClickAction;
        }
        set {
            ((ViewModel)(this.DataContext)).ClickAction = value;
        }
    }
}

有没有人有更好的想法如何做到这一点?

附:这不仅适用于此操作。我有不同的属性需要添加。

【问题讨论】:

  • 但是您的第一个代码示例是在没有代码隐藏的情况下执行此操作的正确方法。这有什么问题?

标签: c# wpf properties attributes


【解决方案1】:

您可以使用attached properties 逻辑将自定义属性添加到您的用户控件,但看起来您必须在不同的视图中为 ClickAction 定义不同的行为,所以我不确定它是否对您有用。我建议您使用路由命令和command bindings - 在这种情况下可能会有所帮助。

【讨论】:

  • 我应该做一个不同的例子。我要添加的属性的类型无关紧要。我只需要一种简单而好的方法来将属性添加到 XAML 用户控件,而无需任何代码。
猜你喜欢
  • 2011-09-02
  • 2020-11-27
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多