WPF ToggleButton.IsChecked绑定无法工作

6

在.NET 3.5中,使用双向绑定到ToggleButton的IsChecked属性是否存在问题?

我有以下XAML代码:

 <ToggleButton 
                    Name="tbMeo"
                    Command="{Binding FilterOnSatelliteTypeCmd}" 
                    IsChecked="{Binding ShowMeoDataOnly, Mode=TwoWay}"
                    ToolTip="Show MEO data only">
                    <Image Source="../images/32x32/Filter_Meo.png" Height="16" />
                </ToggleButton>

我有一个ViewModel,其中包含以下属性:

 private bool _showMeoDataOnly;
    public bool ShowMeoDataOnly
    {
        get { return _showMeoDataOnly; }
        set
        {
            if (_showMeoDataOnly != value)
            {
                _showMeoDataOnly = value;
                RaisePropertyChangedEvent("ShowMeoDataOnly");
            }
        }
    }

如果我点击ToggleButton,ShowMeoDataOnly的值将相应设置。但是,如果我从代码后台将ShowMeoDataOnly设置为true,则ToggleButton的可视状态不会更改以指示IsChecked为true。然而,如果我手动设置ToggleButton的IsChecked属性而不是在代码后台中设置ShowMeoDataOnly为true,则按钮的可视状态会相应更改。
不幸的是,目前无法切换到.NET 4/4.5,因此我无法确认这是否是.NET 3.5的问题。
我的代码有什么问题吗?

你在哪里设置数据上下文? - Bob.
我在包含已发布的XAML的视图加载后立即设置了DataContext。如果这是一个DataContext问题,当单击ToggleButton时绑定到FilterOnSatelliteTypeCmd命令将无法工作,但事实并非如此。 - Klaus Nji
你的Visual Studio的输出选项卡是否显示有错误?例如BindingExpression错误或类似的错误? - Bob.
这就是奇怪的事情。对于这个特定的视图,没有绑定错误。 - Klaus Nji
1
Bob,我搞定了,谢谢。我之前传递的字符串不正确,导致无法触发RaisePropertyChangedEvent事件。 - Klaus Nji
2个回答

7
使用.NET 3.5项目测试,绑定对我来说似乎能够工作。你的ViewModel实现了INotifyPropertyChanged并在设置ShowMeoDataOnly属性时适当地使用它吗?由于你没有发布所有代码,所以很难确定ViewModel正在做什么。
这是我成功运行的代码。当我运行应用程序时,按钮被选中。这是因为ViewModelBase实现了INotifyPropertyChanged,而当设置该属性时,我会执行base.OnPropertyChanged(“ShowMeoDataOnly”)。
MainWindow.xaml:
<Window x:Class="ToggleButtonIsCheckedBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ToggleButtonIsCheckedBinding"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    <Grid>
        <ToggleButton IsChecked="{Binding ShowMeoDataOnly, Mode=TwoWay}">
            Show Meo Data Only
        </ToggleButton>
    </Grid>
</Window>

MainWindowViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ToggleButtonIsCheckedBinding
{
    class MainWindowViewModel : ViewModelBase
    {
        bool _showMeoDataOnly;
        public bool ShowMeoDataOnly {
            get
            {
                return _showMeoDataOnly;
            }

            set
            {
                _showMeoDataOnly = value;
                base.OnPropertyChanged("ShowMeoDataOnly");
            }
        }

        public MainWindowViewModel()
        {
            ShowMeoDataOnly = true;
        }
    }
}

ViewModelBase.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;

namespace ToggleButtonIsCheckedBinding
{
    /// <summary>
    /// Base class for all ViewModel classes in the application.
    /// It provides support for property change notifications 
    /// and has a DisplayName property.  This class is abstract.
    /// </summary>
    public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        #region Constructor

        protected ViewModelBase()
        {
        }

        #endregion // Constructor

        #region DisplayName

        /// <summary>
        /// Returns the user-friendly name of this object.
        /// Child classes can set this property to a new value,
        /// or override it to determine the value on-demand.
        /// </summary>
        public virtual string DisplayName { get; protected set; }

        #endregion // DisplayName

        #region Debugging Aides

        /// <summary>
        /// Warns the developer if this object does not have
        /// a public property with the specified name. This 
        /// method does not exist in a Release build.
        /// </summary>
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        public void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,  
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                string msg = "Invalid property name: " + propertyName;

                if (this.ThrowOnInvalidPropertyName)
                    throw new Exception(msg);
                else
                    Debug.Fail(msg);
            }
        }

        /// <summary>
        /// Returns whether an exception is thrown, or if a Debug.Fail() is used
        /// when an invalid property name is passed to the VerifyPropertyName method.
        /// The default value is false, but subclasses used by unit tests might 
        /// override this property's getter to return true.
        /// </summary>
        protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

        #endregion // Debugging Aides

        #region INotifyPropertyChanged Members

        /// <summary>
        /// Raised when a property on this object has a new value.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises this object's PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">The property that has a new value.</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            this.VerifyPropertyName(propertyName);

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        #endregion // INotifyPropertyChanged Members

        #region IDisposable Members

        /// <summary>
        /// Invoked when this object is being removed from the application
        /// and will be subject to garbage collection.
        /// </summary>
        public void Dispose()
        {
            this.OnDispose();
        }

        /// <summary>
        /// Child classes can override this method to perform 
        /// clean-up logic, such as removing event handlers.
        /// </summary>
        protected virtual void OnDispose()
        {
        }

#if DEBUG
        /// <summary>
        /// Useful for ensuring that ViewModel objects are properly garbage collected.
        /// </summary>
        ~ViewModelBase()
        {
            string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
            System.Diagnostics.Debug.WriteLine(msg);
        }
#endif

        #endregion // IDisposable Members
    }
}

(注:ViewModelBase是从此项目中提取的:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
请注意:ViewModelBase是从该项目中提取的。

2
在.NET 3.5中,RadioButton IsChecked绑定似乎存在问题。这些链接是关于RadioButtons的,但如果上面的代码仍然无法工作,它们可能会提供一种替代方法:http://blogs.msdn.com/b/mthalman/archive/2008/09/04/wpf-data-binding-with-radiobutton.aspx(来源于https://dev59.com/enNA5IYBdhLWcg3wpfiu和https://dev59.com/iXE95IYBdhLWcg3wf-AF)。 - Kyle Tolle
1
Kyle,谢谢您的回复。是的,我的ViewModelBase类实现了INotifyPropertyChanged接口,因此调用了RaisePropertyChangedEvent方法。 - Klaus Nji
Kyle,我在调用RaisePropertyChangedEvent时传递了错误的字符串。你的VerifyPropertName方法帮助我发现了这个问题。有趣的是,我在一个名为Observable的基类中也有这个方法,但这个ViewModel没有从它那里继承。 - Klaus Nji
由于大部分 ViewModel 代码没有发布,我并不清楚可能出现了什么问题。那个 ViewModelBase 代码并不是我的,但我很高兴它能够帮到你! - Kyle Tolle

3

确认您的 DataContext 设置正确。

DataContext = this;

在您的MainWindow.xaml.cs构造函数中编写代码是最简单的方法,假设我们要查看的代码位于MainWindow类中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接