我有一個按鈕,它從文件加載XAML,從中創建一個控件,並將此控件作爲子項添加到作爲模板的一部分的畫布,該畫布是存在於dockpanel資源中的模板的一部分在窗口上。該窗口還有一個名爲cboTColour的組合框和一個名爲cboBColour的組合框,我用它來爲我的加載控件設置一個簡單的漸變背景。加載的XAML不能正確地綁定到現有元素
我加載XAML和使用下面的代碼添加到我的畫布:
XmlReader xaml = XmlReader.Create(filename);
newControl = (Viewbox)XamlReader.Load(xaml);
((Canvas)(testButton.Template.FindName("MyCanvas", testButton))).Children.Clear();
((Canvas)(testButton.Template.FindName("MyCanvas", testButton))).Children.Add(newControl);
這裏是XAML我加載:
<?xml version="1.0" encoding="utf-8"?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Document" Stretch="Fill">
<Canvas Height="64" Width="128" ClipToBounds="True">
<Canvas.Background>
<!--Horizontal Gradient-->
<LinearGradientBrush StartPoint="1,0">
<GradientStop Color="{Binding ElementName=cboTColour, Path=SelectedItem.Name}" Offset="0"></GradientStop>
<GradientStop Color="{Binding ElementName=cboBColour, Path=SelectedItem.Name}" Offset="1"></GradientStop>
</LinearGradientBrush>
</Canvas.Background>
</Canvas>
</Viewbox>
我試圖把XAML直入設計師和它完美的作品,所以這不是一個問題。當我從文件加載XAML時,控件正在創建並正確放置,但數據綁定不起作用 - 顏色不會改變。我收到以下錯誤:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=cboTColour'. BindingExpression:Path=SelectedItem.Name; DataItem=null; target element is 'GradientStop' (HashCode=24393646); target property is 'Color' (type 'Color')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=cboBColour'. BindingExpression:Path=SelectedItem.Name; DataItem=null; target element is 'GradientStop' (HashCode=23972246); target property is 'Color' (type 'Color')
我以爲發生了什麼事是當XAMLReader加載XAML廣告創建一個從它的控制,這是不知道的路徑,我的組合框的,因爲XAML是尚未窗口的一部分,並且當控件添加到窗口時,該綁定不會更新,但我不知道如何修改XAML中的綁定以反映我的組合框相對於它的位置或者修改XAMLReader或整體數據環境以考慮我的控件。我還可以向您保證,當代碼在窗口上按下按鈕時,組合框將按照這一點創建組合框。
我必須指定我不能修改代碼中的綁定本身,因爲綁定將出現在我將加載的不同XAML文件的各個位置和不同時間。
任何幫助將不勝感激。
工作出色,謝謝。 – 2010-07-21 10:15:59