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

时间:2013-09-25 10:19:47

标签: c# wpf properties attributes

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

我希望能够像这样设置Action:

...
<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;
        }
    }
}

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

P.S。这不仅仅适用于此行动。我有不同的属性需要添加。

1 个答案:

答案 0 :(得分:1)

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