簡體   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