繁体   English   中英

绑定到属性值的控件不会更新

[英]Control bound to property value doesn't update

WPF属性绑定存在一些问题。 首先是代码。

C#

public partial class WPFTextBox: UserControl
{
    private bool _bold;
    public bool Bold
    {
        get { return _bold; }
        set
        {
            _bold = value;
            OnPropertyChanged("Bold");
        }
    }

    private bool _selectionChanged;

    public WPFTextBox()
    {
        InitializeComponent();

        DataContext = this;

        Bold = true;  // <--- This works, the checkbox will be checked
        _selectionChanged = false;
     }

     private void txtDetails_SelectionChanged(object sender, RoutedEventArgs e)
     {
         var selection = txtDetails.Selection;
         _selectionChanged = true;
         Bold = selection.FontWeight() == FontWeights.Bold; 
         // ^-- This doesn't work It will trigger everything, but the checkbox won't
         // change value. FontWeight() is an extension I wrote
         _selectionChanged = false;
     }

     private void OnPropertyChanged(string name)
     {
         if(_selectionChanged)
            return; // If the change was brought from the user moving the
                    // cursor in the textbox, don't change the textbox.
         TextRange range = txtDetails.Selection;
         switch(name)
         {
             case "Bold":
                 // change selection to bold, like I mentioned I does work
                 break;
             default:
                 break;
         }
     }
}

XAML

<RichTextBox Name="txtDetails" SelectionChanged="txtDetails_SelectionChanged"/>

<CheckBox Name="chkBold" Content="Bold" IsChecked="{Binding Path=Bold}"/>

我正在创建一个带有格式选项的文本框。 绑定在构造函数中有效,但在选择更改事件中无效。 我尝试将许多选项添加到绑定中,例如Mode=TwoWay以及不同的属性更改触发器。

我使用_selectionChanged bool的原因是,如果我不检查它,如果我有一个单词是其他格式(例如helo) ,然后单击它,它将把所有单词的格式更改为是否大胆。 我认为可能是因为我在选择更改事件中处理它,但是我不确定我还能在其他地方更改属性值。

这里查看示例,您只需抓住INPC部分。

set
{
    _bold = value;
     OnPropertyChanged("Bold");
     NotifyPropertyChanged();
}

您需要继承INotifyPropertyChanged接口

并实现PropertyChangedEventHandler

public class WPFTextBox: UserControl,System.ComponentModel.INotifyPropertyChanged
    {            
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

然后在属性的设置器中调用OnPropertyChanged

1.您也可以使用UpdateSourceTrigger = PropertyChanged事件。 2.是的,对扩展WPF工具包中的控件进行绑定工作。 IsChecked =“ {xcd:Path = Bold}”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM