如何在XAML中为Window或Window属性设置DataContext
在XAML中设置DataContext的两种特殊场景实现方案
通常我们在XAML中为ViewModel设置DataContext时,会采用以下两种方式之一:
<Window.DataContext> <local:MyViewModel/> </Window.DataContext>
或者通过标签绑定到StaticResource(假设未使用Prism等框架)。
针对你提出的两个需求,具体实现方案如下:
1. 在XAML中把DataContext设置为Window本身
要实现和C#代码DataContext = this;相同的效果,有两种常用写法:
使用RelativeSource绑定到自身
直接在Window的DataContext属性中绑定当前实例,无需额外命名:<Window x:Class="YourNamespace.YourWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <!-- 窗口内容 --> </Window>使用ElementName绑定(需给Window命名)
先给Window设置x:Name,再绑定到这个名称:<Window x:Class="YourNamespace.YourWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="CurrentWindow" DataContext="{Binding ElementName=CurrentWindow}"> <!-- 窗口内容 --> </Window>
2. 给单个控件临时设置DataContext为Window的某个属性
假设你的Window有一个名为UserProfile的属性(比如包含Nickname字段的自定义类),要让TextBox的DataContext指向这个属性,有两种实现方式:
直接设置控件的DataContext
通过RelativeSource找到父级Window,绑定到目标属性作为控件的DataContext,之后控件内部的绑定就可以直接指向该属性的子字段:<TextBox DataContext="{Binding UserProfile, RelativeSource={RelativeSource AncestorType=Window}}" Text="{Binding Nickname}"/>不修改DataContext,直接使用完整绑定路径
如果不想改动控件的DataContext,也可以直接在绑定中写出完整的层级路径:<TextBox Text="{Binding UserProfile.Nickname, RelativeSource={RelativeSource AncestorType=Window}}"/>
内容的提问来源于stack exchange,提问作者A.B.
相关产品推荐
相关产品推荐

