gpt4 book ai didi

WPF 单向绑定(bind)损坏

转载 作者:行者123 更新时间:2023-12-04 01:57:36 28 4
gpt4 key购买 nike

我试图将 2 个不同的 WPF 控件绑定(bind)到 ViewModel 中的同一属性,即 CheckBox.IsChecked 和 Expander.IsExpanded。我想要实现的行为是让 CheckBox 影响 ViewModel(因此也影响 Expander),但不是其他方式绑定(bind)。
就像是:

Checkbox Checked -> ViewModel property set to frue -> Expander.Expand
Checkbox Unchecked -> ViewModel property set to false -> Expander.Collapse
Expander Expanded -> Nothing else affected
Expander Collapsed -> Nothing else affected

这是 XAML:
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Expander IsExpanded="{Binding IsChecked, Mode=OneWay}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked}" Content="Is Checked"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>
</Window>

和守则:
using System.ComponentModel;
using System.Windows;

namespace WpfApplication9
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}

public class ViewModel: INotifyPropertyChanged
{
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
NotifyPropertyChange("IsChecked");
}
}

protected void NotifyPropertyChange(string PropertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}

public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
}

现在我的问题是,只要我点击 Expander 展开/折叠它,Binding 似乎就停止工作了。谁能向我解释为什么会发生这种情况以及我如何实现这一目标?提前致谢!

最佳答案

新答案

发现您可以通过设置 UpdateSourceTrigger 来做到这一点至Explicit在您的扩展器上。这将绑定(bind)保持为双向,但永远不会更新源,因为您告诉它不要更新源,除非您明确告诉它。

<Expander IsExpanded="{Binding IsChecked, UpdateSourceTrigger=Explicit}">
<Expander.Header>
<CheckBox IsChecked="{Binding IsChecked}" Content="Is Checked"/>
</Expander.Header>
<TextBlock Text="Expanded!"/>
</Expander>

将我的旧答案留在下面,以便评论有意义,并且因为我仍然觉得 View 特定代码在 View 的代码隐藏中没有问题:)

旧答案

就个人而言,因为这是特定于 View 的代码,所以我认为使用 CheckBox 单击事件来设置 Expander 的 IsExpanded 没有问题。值(value)。
private void MyCheckBox_Click(object sender, RoutedEventArgs e)
{
MyExpander.IsExpanded = ((CheckBox)sender).IsChecked.GetValueOrDefault();
}

您可以通过删除名称并导航 Visual Tree 以找到与 CheckBox 关联的 Expander 来使其更加通用。这是一个使用一些 Visual Tree Helpers I built 的示例
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
var chk = (CheckBox)sender;
var expander = VisualTreeHelpers.FindAncestor<Expander>(chk);

if (expander != null)
expander.IsExpanded = chk.IsChecked.GetValueOrDefault();
}

关于WPF 单向绑定(bind)损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680564/

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