【问题标题】:Dependency Property stops updating after target property changes due to edit in UI由于 UI 中的编辑导致目标属性更改后,依赖属性停止更新
【发布时间】:2014-08-04 16:27:19
【问题描述】:

我的控件上有一个自定义依赖属性,如下所示(实现控件的样板):

public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
    "Value",
    typeof(String),
    typeof(BindingTestControl),
    new PropertyMetadata(null));

public static void SetValue(UIElement element, string value)
{
    element.SetValue(ValueProperty, value);
}
public static string GetValue(UIElement element)
{
    return (string)element.GetValue(ValueProperty);
}

我创建了一个带有代码隐藏的页面,以便与相关的 xaml 绑定,如下所示(页面上有x:Name="root"):

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <local:BindingTestControl Value="{Binding ElementName=root, Path=StringItem}"/>
    <Button Width="200" Height="100" Tapped="Button_Tapped" FlowDirection="RightToLeft"/>
</Grid>

像这样使用代码隐藏(同样,只显示相关部分):

private string stringItem = "";
public string StringItem
{
    get
    {
        return stringItem;
    }
    set
    {
        this.stringItem = value;
        OnPropertyChanged("StringItem");
    }
}

int i = 0;
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
    //i++;
    this.StringItem = "Test" + i;
}

这第一次工作正常,但如果我更新文本框中的值,绑定不会覆盖新值。如果我取消注释i++;,那么每次绑定都会覆盖。我假设发生这种情况是因为INotifyPropertyChanged 发送的值与前一个值相同,尽管Textbox 中的值不再相同。

有没有办法强制通过绑定的值,即使它没有改变?

【问题讨论】:

  • 请检查输出窗口。它应该向您显示更新出价来源等时发生的任何错误

标签: binding windows-runtime winrt-xaml dependency-properties


【解决方案1】:

您可以将您的设置器更改为 -

set
{
    this.stringItem = null;
    this.stringItem = value;
    OnPropertyChanged("StringItem");
}

当值发生变化时应该强制触发 PropertyChanged 事件。

【讨论】:

  • 这就是我最终要做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多