我是wpf和xaml的新手。我通過在這裏搜索或在網上搜索找到大多數問題(用其他語言)的解決方案,但這個讓我發瘋。我在谷歌上搜索了很多並瀏覽了很多論壇,但似乎這次我遇到了一個真正的挑戰!如何在運行時動態更改MultiBinding(或任何其他)資源的ConverterParameter(或任何)屬性?
我在Window.Resources下面的代碼:
<my:NameConverter x:Key="NameConverter"/>
<MultiBinding x:Key="CustomerFullNameBinding"
Converter="{StaticResource NameConverter}"
ConverterParameter="LastNameFirst">
<Binding Path="FirstName" />
<Binding Path="MiddleName" />
<Binding Path="LastName" />
</MultiBinding>
的NameConverter類組合名稱的各個部分返回全名。返回值是基於ConverterParameter的值可以是下列之一:FirstNameFirst,LastNameFirst,OnlyFirstName,OnlyLastName,縮寫(有幾個,但爲了簡單起見,我們不考慮它們)
此代碼工作正常。我用下面得到的結果:
<TextBlock Text="{DynamicResource CustomerFullNameBinding}"/>
然而,問題是,如果我使用資源CustomerFullNameBinding 20次在我的代碼(如abovw所示),他們都將在一個特定的格式顯示名稱。 (即在這裏,在CustomerFullNameBinding的聲明我已經設置ConverterParameter =「LastNameFirst」因此所有20個引用將只有這樣顯示的名字。)
現在我的問題是我可以使它更「廣義」,使我可以動態設置值ConverterParameter?即我可以有多個文本塊,可以顯示不同格式的全名。我知道這是可能的,如果我們創建多個資源,如如下:
<MultiBinding x:Key="CustomerFullNameBinding_FirstNameFirst"
Converter="..." ConverterParameter="FirstNameFirst">
......
</MultiBinding>
<MultiBinding x:Key="CustomerFullNameBinding_LastNameFirst"
Converter="..." ConverterParameter="LastNameFirst">
......
</MultiBinding>
<MultiBinding x:Key="CustomerFullNameBinding_OnlyFirstName"
Converter="..." ConverterParameter="OnlyFirstName">
......
</MultiBinding>
... and so on ...
,但我不想說,「怎麼它會真的讓我的代碼太笨重,而且最重要的是它會作廢資源的可重用性的概念!
請給我建議任何可能的解決方案。
在此先感謝。
注:我從here得到了最初的想法。可以找到類似的工作示例msdn.microsoft.com/en-us/library/ms771336.aspx。
標籤:WPF XAML靜態資源dynamicresource結合
非常感謝您的快速回復。 你是真的。 ConverterParameter是一個普通屬性,而不是一個DependencyProperty。其實我是WPF的新手,有時我也忘記了基本概念!將用戶控件綁定到返回結構而不是字符串的動態資源是一個好主意。我沒有真的嘗試過,但我確定它會工作!再一次感謝你!!! – mg007 2009-08-14 10:58:00