簡體   English   中英

WPF ListView中的轉換器,使用緩存的值作為參數

[英]Converter in WPF ListView using cached value as parameter


我有一個管理不同類型文檔的應用程序。 在文檔管理器中,我在ListView中顯示文檔。 我創建了一些轉換器,以在不弄亂文檔類本身的情況下顯示文檔的特殊aspacts。 列表視圖中的一列應顯示一個代表文檔類型和文檔編號的圖標。 列應如下所示

 <icon> D 1 <icon> D 11 ... 

文件編號應在左側填充以適合最大編號。

目前,我有一個轉換器,可以創建所需的字詞

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
D{
    System.Windows.Controls.ListView view = (System.Windows.Controls.ListView)parameter;
    int count = (view.Items.Count.ToString().Count());
    string id = "D" + value.ToString().PadLeft(count);
    return id;
}

轉換器用於CellTemplate,其中轉換器參數是listview本身

<TextBlock Text="{Binding Number, Converter={StaticResource docIDConverter}, ConverterParameter={x:Reference Documents}}" />

我知道項目中的文檔數量,可以將其作為窗口類的屬性來提供

    /// <summary>
    /// The amount of documents contained in a project
    /// </summary>
    int documentCount = 0;
    public int DocumentCount {
        get { 
            if(this.documentCount == 0)
                documentCount = Project.Documents.Count;
            return documentCount;
        }
    }

這行得通,但我認為這是不好的風格,在大名單上可能會很慢。

如何使用屬性DocumentCount作為轉換器的參數。 或者如何在多值轉換器中將屬性DocumentCount用作綁定對象感謝Clemens Hoffmann

ConverterParameters不是依賴項屬性。 因此,您無法綁定到它們。 但是您可以使用多重綁定獲得相同的效果:

<Style TargetType="FrameworkElement">
    <Setter Property="Text">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource docIDConverter}">
                <Binding Path="DocumentCount" RelativeSource="RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>
</Style>

現在,多值轉換器將源值數組作為輸入:

public class AccessLevelToVisibilityConverter : IMultiValueConverter {
    public object Convert(
            object[] values, Type targetType, object parameter, CultureInfo culture)
       {
            int count = values.All(v => (v is int);
            string id = "D" + values.All(v => (v is TypeYouAreExpectingHere).ToString().PadLeft(count);
            return id;
        }

        public object[] ConvertBack(
            object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

暫無
暫無

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

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