我有一個簡單的視圖,我想綁定到我的ViewModel。我目前使用Source =格式進行數據綁定,但是想將其轉換爲在代碼中指定DataContext。在代碼中指定DataContext
這是我和它的工作...
XAML:
<Window.Resources>
<local:ViewModel x:Key="ViewModel" />
</Window.Resources>
<Button Content="Click">
<local:EventToCommand.Collection>
<local:EventToCommandCollection>
<local:EventToCommand Event="Click" Command="{Binding Source={StaticResource ViewModel}, Path=ClickCommand, diag:PresentationTraceSources.TraceLevel=High}" />
<local:EventToCommand Event="GotFocus" Command="{Binding Source={StaticResource ViewModel}, Path=GotFocusCommand}" />
</local:EventToCommandCollection>
</local:EventToCommand.Collection>
</Button>
</Window>
視圖模型代碼:
public class ViewModel
{
public Command ClickCommand { get; set; }
public Command GotFocusCommand { get; set; }
public ViewModel()
{
ClickCommand = new Command((obj) => { Execute(obj); return null; });
GotFocusCommand = new Command((obj) => { Execute(obj); return null; });
}
void Execute(object param)
{
if (param != null)
System.Windows.MessageBox.Show(param.ToString());
else
System.Windows.MessageBox.Show("Execute");
}
}
現在我想做的是這在我窗口的代碼背後:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
並刪除XAML中的Window.Resources部分,但我無法弄清楚如何相應地更改我的綁定字符串。
你是什麼意思是「你不知道」嗎?你沒有訪問XAML代碼?你不能從你在XAML上使用的每一個綁定表達中移除'Source = {StaticResource ViewModel}'部分嗎?如果你這樣做,數據將從'DataContext'本身獲取。 –
請看我下面的評論... – Oliver
@Olivger,根據http://adammills.wordpress.com/2011/02/14/eventtocommand-action-mvvm-glue/什麼@Rachel說應該工作。請參閱您的視覺工作室的'輸出'窗口,並檢查您是否收到任何綁定錯誤 ... –