XAML设置两个上下文
时间: 2023-07-04 18:07:22 浏览: 44
在 XAML 中设置两个上下文,可以使用 `x:Reference` 指令来引用指定的对象。例如,假设我们有一个 `DataContext1` 对象和一个 `DataContext2` 对象,我们可以在 XAML 中这样设置两个上下文:
```xml
<StackPanel>
<StackPanel.DataContext>
<local:DataContext1/>
</StackPanel.DataContext>
<Button Content="Button 1" Command="{Binding Command1}" />
<Button Content="Button 2" Command="{Binding DataContext2.Command2, Source={x:Reference Name=stackPanel}}" />
<StackPanel.DataContext>
<local:DataContext2 x:Name="dataContext2"/>
</StackPanel.DataContext>
</StackPanel>
```
在上面的例子中,我们在 `StackPanel` 标记中设置了两个 `DataContext`。第一个是 `DataContext1`,它是 `StackPanel` 的默认上下文。第二个是 `DataContext2`,它是 `Button 2` 的上下文。
我们使用 `x:Reference` 指令来引用 `StackPanel`,并使用 `Source` 属性来指定引用的对象。然后,我们绑定 `Command2` 到 `DataContext2` 中的命令。注意,我们使用了 `DataContext2` 的 `x:Name` 属性来在 XAML 中创建一个引用。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)