引用mvvmlight dll ,操做command

前言

由於vs2010沒有集成mvvmlight 因此想要使用mvvmlight的relaycomman須要引用dll
須要測試某個功能的時候,不能進行快帶的集成後端

引用mvvmlight dll

若是之前有其它版本的vs能過nuget安裝過,則目錄 是:mvvm

c:\users\administrator.xdmwiwrtm7kc37y\documents\visual studio 2013\Projects\WpfApplication2\packages\MvvmLightLibs.4.2.30.0\lib\net40

引用函數

GalaSoft.MvvmLight.WPF4.dll

如何實現

xaml中的代碼以下:

放一個button ,指定Button的命令是TestN, 這裏是隨便寫的,全符合命名規範測試

注意:Datacontext的指定 ,若是不指定 ,命令不會觸發。這裏不加新類,直接寫在CS裏面。this

就是爲了測試而測試spa

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfApplication2="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        >
    <Grid >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button Command="{Binding TestN}" Width="100" Height="100" Content="wefwfwef"/>
    </Grid>

</Window>

注意:
若是沒有如下這句,會報錯code

DataContext="{Binding RelativeSource={RelativeSource Self}}"

cs後端的代碼以下

public partial class MainWindow : Window
    {
        private RelayCommand _testN;

        public MainWindow()
        {
            InitializeComponent();
            //DataContext = this;
        }

        public RelayCommand TestN
        {
            get { return _testN??(_testN=new RelayCommand(() =>
            {
                TestNMethod();
            })); }
            set { _testN = value; }
        }

        private void TestNMethod()
        {
            throw new NotImplementedException();
        }
    }

注意:
若是xaml中沒有指定 datacontxt,則要在構造 函數中指定datacontext是本類。xml

調用之後TestNMethod()方法會被觸發。get

相關文章
相關標籤/搜索