gpt4 book ai didi

c# - 在 WPF 中取消设置/更改绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:55 25 4
gpt4 key购买 nike

如何取消设置应用于对象的绑定(bind),以便我可以从不同的位置对其应用另一个绑定(bind)?

假设我有两个数据模板绑定(bind)到相同的对象引用

数据模板 #1 是要加载的默认模板。我尝试将按钮命令绑定(bind)到 Function1来 self 的 DataContext 类:

<Button Content="Button 1" CommandParameter="{Binding }" Command="{Binding DataContext.Function1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

这实际上有效并且函数被绑定(bind)。但是,当我尝试将数据模板 #2 加载到同一对象时(同时尝试将另一个按钮命令绑定(bind)到来 self 的 DataContext 类的不同函数(Function2)):

<Button Content="Button 2" CommandParameter="{Binding }" Command="{Binding DataContext.Function2, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

它不起作用,第一个绑定(bind)仍然是执行的那个。有解决方法吗?

编辑(为了更好的问题上下文):

我在我的 Window.Resources 中定义了我的模板:

<Window.Resources>
<DataTemplate DataType="{x:Type local:ViewModel1}">
<local:View1 />
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}">
<local:View2 />
</DataTemplate>
</Window.Resources>

View1.xaml 和 View2.xaml 包含我上面描述的按钮定义(我希望它们控制我的流程)。ViewModel1 和 ViewModel2 是我实现接口(interface) IPageViewModel 的 ViewModel这是我的变量类型 CurrentPageViewModel .

在我的 XAML 中,我绑定(bind)了 ContentControl到变量 CurrentPageViewModel :

<ContentControl Content="{Binding CurrentPageViewModel}" HorizontalAlignment="Center"/>

在我的 .CS 中,我有一个定义为 List<IPageViewModel> PageViewModels 的列表,我用它来包含我的两个 View 模型的实例:

PageViewModels.Add(new ViewModel1());
PageViewModels.Add(new ViewModel2());

// Set starting page
CurrentPageViewModel = PageViewModels[0];

当我尝试更改我的 CurrentPageViewModel 时到另一个 View 模型,这是我希望新绑定(bind)起作用的时候。不幸的是,事实并非如此。我做事的方式是否正确?

最佳答案

如果出于某种原因您不能只使用两个不同的数据模板,通常是因为数据模板非常大或复杂,我建议使用 ContentControlDataTemplateSelector .

在您的数据模板中放置另一个 ContentControl ,创建 2 个仅包含您的按钮的 DataTemplates,一个带有 Function1,一个带有 Function2。创建 DataTemplateSelector并将其设置在初始 ContentControl 上。 DataTemplateSelector现在只需要根据决定选择合适的模板,例如项目的类型或项目的属性等。

关于c# - 在 WPF 中取消设置/更改绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17400815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com