2010-12-13 73 views
4

我想將我的MultiDataTrigger.Conditions綁定到單選按鈕,但它不起作用。這是我的場景。找不到與參考綁定的源

在wpf中,我有一個GridPanel,它假設有一個單選按鈕。

我生成動態單選按鈕進入GridPanel中,像這樣:

RadioButton allAccountBtn = new RadioButton(); 
allAccountBtn.Name = "allAccountBtn"; 
GridPanel.Children.Add(allAccountBtn); 

然後在我的XAML中,我有一個圖像按鈕,這將改變基於這個單選按鈕選擇,而另一個控制的財產。

這裏是我的代碼:

<Button> 
<Button.Template> 
     <ControlTemplate> 
       <Image Name="addFolderIcon" Source="Icon/Decoration/folderColor.png"> 
       <ControlTemplate.Triggers> 
         <MultiDataTrigger> 
          <MultiDataTrigger.Conditions> 
            <Condition Binding="{Binding Tag, ElementName=folderBackBtn}" Value="{x:Null}"/> 
            <Condition Binding="{Binding IsChecked, ElementName=allAccountsBtn}" Value="True"/> 
          </MultiDataTrigger.Conditions> 
          <Setter Property="Control.IsEnabled" Value="False"/> 
          <Setter TargetName="addFolderIcon" Property="Source" Value="Icon/Decoration/folder.png"/> 
         </MultiDataTrigger> 
       </ControlTemplate.Triggers> 
     </ControlTemplate> 
</Button.Template> 
</Button> 

當我運行程序時,它顯示的錯誤代碼:「爲參照結合找不到來源」,並在條件返回第二個條件爲假(的ElementName = allAccountsBtn)

這是爲什麼發生?

任何方式可以引用從動態命名和生成的RadioButton獲取IsChecked屬性?

+0

如果我在我的xaml中添加單選按鈕,它可以被檢測到,所以現在的問題是,ElementName找不到動態生成的控件。 – VHanded 2010-12-14 02:32:32

回答

1

讓我們來定位問題。 嘗試將XAML中的RadioButton直接添加到您的GridPanel中,而不是在C#中。 如果錯誤仍然存​​在,那麼問題不在於添加控件的動態方式。

我認爲模板下控件的'可見性'有一個問題。您可以調用yourButton.ApplyTemplate()來強制構建可視化樹。但不確定在XAML中如何做到這一點。

+0

是的,問題是動態生成的RadioButton。我在本地添加RadioButton,並且它沒有錯誤。 我在調用GridPanelChildren.Add(allAccountsBtn)後調用GridPanel.ApplyTemplate(),沒有任何事情發生。同樣發生在allAccountsBtn.ApplyTemplate()... 我必須動態地包含RadioButton,因爲數據來自數據庫。 – VHanded 2010-12-13 10:17:17

+0

從某處讀取,動態生成的控件具有與本地控件不同的命名空間,但我不知道如何處理此線索。 – VHanded 2010-12-13 10:21:25

+0

沒關係,我爲它找到了解決方法。謝謝。 – VHanded 2010-12-14 05:42:28

2

我注意到您將動態生成的對象的屬性設置爲「allAccountBtn」(單數「Account」),但您的XAML的ElementName引用了「allAccountsBtn」(複數「Accounts」)。嘗試改變他們是相同的。