簡體   English   中英

數據綁定+轉換器不更新綁定屬性-XAML-WPF

[英]Data Binding + Converter doesn't update bound property - XAML - WPF

我想要的是:

將可觀察的集合綁定到屬性(例如Opacity ),該屬性應采用轉換器類的返回值。


XAML代碼:

    <ListBox x:Name="HostDeviceList" 
            ItemsSource="{Binding ObservableCollection}" 
            SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.Background>
        <ImageBrush ImageSource="assets/Tapako.ico" 
                    Opacity="{Binding ObservableCollection, Converter={StaticResource IsNullToFloatConverter}}" Stretch="None">
        </ImageBrush>
    </ListBox.Background>

我的轉換器課程:

public class IsNullToFloatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    float lowValue = 0.1f;
    float highValue = 0.5f;

    if (parameter is float && value != null)
    {
        return parameter;
    }
    else
    {
        if (value is IEnumerable)
        {
            if (((IEnumerable)value).Any())
            {
                return lowValue;
            }
            else
            {
                return highValue;
            }
        }
        if (value != null)
        {
            return lowValue;
        }
        else
        {
            return highValue;
        }
    }
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    throw new NotImplementedException();
}
}

什么有效:

  1. ListView已正確更新
  2. 如果我不使用轉換器類,而是使用Opacity="{Binding ObservableCollection.Count}" ,則第一個元素出現后,不透明度就會從0變為1。

什么不起作用:如果我使用轉換器,則在啟動時只調用一次Convert ,但是在ListView出現新元素時不調用Convert

您的集合很可能沒有發生變化(我是指對集合的引用),因此您必須實現一種機制來處理集合更改事件(在添加或刪除值時觸發)

注意:在兩種情況下,您都需要更改轉換器以直接使用計數

因此 ,如果它無法解決問題, 那么您應該能夠做到這一點 ->意味着該集合在計數更改時不會通知您,您需要走更長的路,如下所述:

<ImageBrush ImageSource="assets/Tapako.ico" 
            Opacity="{Binding ObservableCollection.Count, Converter={StaticResource IsNullToFloatConverter}}" Stretch="None">
</ImageBrush>

如果上述方法不起作用,我會這樣做:

創建一個新屬性->我將在VM中將CollectionCount綁定到的新屬性

public int collectionCount;

public int CollectionCount
{
    get
    {
        return collectionCount;
    }
    set
    {
        collectionCount = value;
        RaisePropertyChanged("CollectionCount");
    }
} 

更改綁定以使用它而不是整個集合

<ImageBrush ImageSource="assets/Tapako.ico" 
            Opacity="{Binding CollectionCount, Converter={StaticResource IsNullToFloatConverter}}" Stretch="None">
</ImageBrush>

注冊收集更改並創建一個處理程序,該處理程序會將計數賦予您的屬性,該屬性將在更改時觸發並調用轉換器

ObservableCollectionProp.CollectionChanged += CollectionChangedHandler;

private void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)
{
    CollectionCount = ObservableCollectionProp.Count;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM