【问题标题】:Binding not working on Label绑定在标签上不起作用
【发布时间】:2014-11-18 20:22:08
【问题描述】:

这一定很明显,但是谁能告诉我为什么我标签中的值只更新一次。我的 PropertyChangedEventHandler 永远不会触发:

<Page.Resources>
   x:Key="SoSummaryViewModelDataSource"/>
</Page.Resources>
<Grid DataContext="{StaticResource SoSummaryViewModelDataSource}">
   <Label Grid.Row="2" 
          Margin="30, 0, 0, 0" 
          FontWeight="Medium"
          Content="{Binding TotalDisplayedCustomers, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

这是我的财产:

    public string TotalDisplayedCustomers
    {
        get { return _totalDisplayedCustomers; }
        set 
        {
            if (_totalDisplayedCustomers != value)
            {
                _totalDisplayedCustomers = value;
                OnPropertyChanged("TotalDisplayedCustomers");                
            }
        }
    }

这是我的 OnPropertyChanged:

    protected void OnPropertyChanged(string propertyName)
    {
        //when propertyName is TotalDisplayedCustomers, handler is null, why??
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

【问题讨论】:

  • 你尝试过简单的谷歌搜索吗?也看看这个例子stackoverflow.com/questions/17233651/…
  • @user2348184 你如何更改TotalDisplayedCustomers 以便PropertyChangedEventHandler 永远不会触发
  • @DJKRAZE 是的,我有一个吸气剂,所以不确定你的样本有什么用途,你能详细说明一下吗?
  • @user2348184 - 最有可能的实例不同。您确定只在实例SoSummaryViewModelDataSource 上设置值吗?
  • @user2348184 加载 ObservableCollection 后,我将 TotalDisplayedCustomers 设置为这样,TotalDisplayedCustomers = string.Format("Customers: {0}", _summaryLineItems.Count);

标签: c# wpf xaml dependency-properties


【解决方案1】:

您是否尝试检查您的 ViewModel 加载到您的 DataContext 中。当我想检查它时,我使用Wpf Inspector Tools

【讨论】:

  • 我没试过,我去下载看看,谢谢指点!
【解决方案2】:

这就是我想出的,我仍然不明白我的绑定出了什么问题,但是我没有依赖 PropertyChanged 在我的视图模型中触发 string,而是绑定了我的 @ 987654323@ 到 ObservableCollectionCount 属性。

首先我在页面上使用了 DataContext:

<Page.DataContext>
   <vm:SoSummaryViewModel/>
</Page.DataContext>

像这样更改了我的 TextBlock:

<TextBlock Grid.Row="2" Margin="40, 0, 0, 0">
            <Run Text="Customer Count: " FontWeight="Medium"></Run>
            <Run Text="{Binding SummaryLineItems.Count, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}">
            <TextBlock Text=" (Filtered)" Visibility="{Binding HideOnTimeCustomers, Converter={StaticResource showIfTrue}}"/>                           
</TextBlock>

【讨论】:

    猜你喜欢
    • 2018-04-07
    • 1970-01-01
    • 2018-02-04
    • 2020-08-06
    • 2010-10-22
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2017-12-11
    相关资源
    最近更新 更多