我是新來WPF和這個奇特結合的東西,接着這些tutorial和得到這個XAML
:如何將命令綁定到按鈕
<Button
x:Name="btn"
Content="refresh"
Command="{Binding RefreshCmd}" />
和驗證碼:
public someClass()
{
InitializeComponent();
CreateRefreshCmd();
btn.DataContext=this; // without this line it will not work !!
}
public ICommand RefreshCmd
{
get;
internal set;
}
private bool CanExecuteRefreshCmd()
{
return true;
}
private void CreateRefreshCmd()
{
RefreshCmd=new RelayCommand(e => RefreshExec(), c => this.CanExecuteRefreshCmd());
}
public void RefreshExec()
{
// do something fancy here !
}
但沒有構造函數中的最後一行它將不起作用。
在教程中這行不存在。
我該如何避免這種情況?
編輯:
我點擊了與Visual Studio中的數據綁定和得到這個:
Command="{Binding RefreshCmd, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:spielerei}}}"
這真的有必要嗎?
在DataContext可能會在您的教程視圖的XAML來設置。 http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx –