繁体   English   中英

如何在没有代码的情况下向UserControl添加属性/属性?

[英]How to add a Property/Attribute to UserControl with no Code behind?

首先,是否可以在没有代码的情况下向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;
        }
    }
}

有人有更好的主意该怎么做吗?

附注:这不仅是为了该操作。 我需要添加其他属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM