Silverlight實用竅門系列:63.Silverlight中的Command,自定義簡單Command


    在Silverlight中的MVVM模式下將前台頁面和ViewModel界面交互分離開是通過本節所要講述的Command實現的。我們自定義一個Command需要繼承於ICommand接口並且實現這個接口。它有CanExecute()、Execute()方法和CanExecuteChanged事件組成。

      CanExecute():判斷是否繼續執行操作。

      Execute():執行操作的內容。

      CanExecuteChanged:當出現影響是否應執行該命令的更改時發生。

    首先:自定義的一個btnCommand。

    public class btnCommand:ICommand
{
private bool canExe;
/// <summary>
/// 構造函數設置是否執行操作
/// </summary>
/// <param name="canexe"></param>
public btnCommand(bool canexe)
{
this.canExe = canexe;
}

/// <summary>
/// 判斷是否執行操作
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
if (canExe)
{
return true;
}
return false;
}

/// <summary>
/// 是否執行操作的變更發生時
/// </summary>
public event EventHandler CanExecuteChanged;

/// <summary>
/// 執行操作的內容,可以變為Action行為
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
if (parameter != null)
{ MessageBox.Show(parameter.ToString()); }
else
{
MessageBox.Show("未設置CommandParameter");
}
}
}

    其次:定義一個ViewModel,並且在構造函數中初始化兩個Command屬性。

    public class BtnViewModel
{
// 設置兩個命令
public ICommand BtnCommand { get; set; }
public ICommand BtnCommandTrue { get; set; }
public BtnViewModel()
{
//初始化兩個命令值
BtnCommand = new btnCommand(false);
BtnCommandTrue = new btnCommand(true);
}
}

    再次將ViewModel初始化為頁面數據源

    <UserControl.DataContext>
<local:BtnViewModel />
</UserControl.DataContext>

    最后:前台的兩個按鈕綁定Command

    <Grid x:Name="LayoutRoot" Background="White">
<Button Content="第一個" Height="23" HorizontalAlignment="Left"
Command="{Binding BtnCommand}" CommandParameter="第一個Command"
Margin="94,80,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
<Button Command="{Binding BtnCommandTrue}" CommandParameter="第二個Command"
Content="第二個" Height="23" HorizontalAlignment="Left" Margin="94,140,0,0"
Name="button2" VerticalAlignment="Top" Width="75" />
</Grid>

    如需源碼請點擊 SLICommand.zip 下載,下面是效果圖。有一個按鈕CanExecute,有一個不能點擊。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM