在代码中指定DataContext
我有一个简单的视图,我想将其绑定到我的 ViewModel。我目前正在使用 Source= 格式进行数据绑定,但希望将其转换为在代码中指定 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>
ViewModel Code:
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");
}
}
现在我想做的就是在我的 Window 后面的代码中执行此操作:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
并删除 XAML 中的 Window.Resources 部分,但我不知道应该如何做相应地更改我的绑定字符串。
I have a simple View that I want to bind to my ViewModel. I am currently using the Source= format for the data binding, but would like to convert that into specifying the DataContext in code.
This is what I have and it is working ...
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>
ViewModel Code:
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");
}
}
Now all I want to do is this in my Window's code behind :
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
and remove the Window.Resources section in XAML, but I can not figure out how I should change my Binding strings accordingly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DataContext
是默认的Source
,所以这应该可以工作:The
DataContext
is the defaultSource
, so this should work: