2009-12-04 168 views
0

我在我的部分有一個模板。我想將該模板中某個值的寬度綁定到我的Main XAML部分中的控件寬度。WPF數據綁定 - 從模板綁定到UI控制

可以這樣做嗎? Expression Blend僅在「綁定」列表中顯示模板。

例如,這是我希望有工作的內容:

<Windows.Resources> 
... My template stuff 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="20" /> 
     <ColumnDefinition Width="50" /> 
     <ColumnDefinition Width="{Binding ElementName=SecondColumn, Path=Width}"/> 
     <ColumnDefinition Width="30" /> 
    </Grid.ColumnDefinitions> 
... More template stuff 
</Windwos.Resources> 

<Grid Name="MainGrid"> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition Name="FirstColumn" Width=".25*" /> 
     <ColumnDefinition Name="SecondColumn" Width=".5*" /> 
     <ColumnDefinition Name="ThirdColumn" Width=".25*" /> 
    </Grid.ColumnDefinitions> 
... Rest of my XAML 

回答

1

一旦進入模板,您就會與其他元素分離(有充分的理由 - 可以在其他地方重用)。在這種情況下(假設模板在「MainGrid」下的某個地方使用),看起來您可以使用RelativeSource FindAncestor Binding來定位父級網格(您需要確保計算VisualTree中的網格以獲得正確的AncestorLevel - 只是在這裏的代碼將是2)。路徑將是ColumnDefinitions [1] .Width。請記住,這取決於您維護使用模板的元素的結構,因此它有點脆弱。還有一種使用SharedSizeGroup的替代方法,它可以連接不同級別的Grid Rows或Columns,但只適用於Auto和固定像素大小。這種綁定方法適用於固定和*尺寸。

完整的結合:

Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}, AncestorLevel=2}, Path=ColumnDefinitions[1].Width}" 
1

你的意思是你希望你的列總是相同的寬度或你的意思,起初,他們是在同一寬度?如果是這樣,爲什麼不定義一個樣式並在兩列中使用它?