首先,是否可以在没有代码的情况下向 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;
}
}
}
有没有人有更好的想法如何做到这一点?
PS这不仅仅是为了这个动作。我有不同的属性需要添加。