簡體   English   中英

將WPF擴展工具包PropertyGrid綁定到字典或其他動態源?

[英]Bind WPF Extended Toolkit PropertyGrid to a dictionary or other dynamic source?

我有一個包含多個子元素的XML文件。 每個子元素都包含一系列元素,但XML模式未記錄,因此我無法考慮每個可能的元素名稱。 我的目標是為每個子元素提供編輯器視圖。 例如:

XML文件

<root>
    <element>
        <subelement1>value</subelement>
        <randomName88787>value</randomName>
        <somethingTotallyFunky>value</somethingTotallyFunky>
        <iHaveNoIdeaWhatThisWillBe>value</iHaveNoIdeaWhatThisWillBe>
    </element>
</root>

我希望使用WPF Toolkit的PropertyGrid控件(或類似的東西)來呈現<element>的所有子元素的<element> ,但是此控件被設計為綁定到CLR對象。 當然我無法定義具有屬性的類,因為我不知道這些屬性是什么。 我已經嘗試將以下代碼綁定到expando對象:

var expando = new ExpandoObject();
var dict = (IDictionary<string, object>)expando;
foreach (var prop in unit.Elements())
{
    if (dict.ContainsKey(prop.Name.LocalName) == false)
    {
        dict.Add(prop.Name.LocalName, (string)prop.Value);
    }
}

Properties.SelectedObject = expando;

但是沒有顯示任何屬性。 它似乎沒有很好地處理ExpandoObject。 有沒有更好的方法來接近我正在嘗試做的事情? 有更好的控制來做到這一點?

看看這個 ,它基本上應該解釋一切。 簡而言之,實現ICustomTypeDescriptor(在從ExpandoObject派生的類型上)應該可以正常工作; 我看了一下Extended WPF Toolkit源代碼,我認為它會正確處理它。

實際上,您可以不使用任何自定義對象來執行此操作。 在名為data.xml的文件中使用您的示例數據嘗試此XAML:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <XmlDataProvider x:Key="data" Source="data.xml" XPath="/root/element/*"/>
</Window.Resources>
<Grid>
    <ListView ItemsSource="{Binding Source={StaticResource data}}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Tag" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Label Content="{Binding Path=Name}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Value" Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Path=InnerText}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>
</Window>

我希望您能找到用戶在XmlDataProvider.Document中更改的任何值,因此保存該值應該保留用戶的更改。

暫無
暫無

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

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