开发者

WPF Data Binding - Bind to UI Control from a Template

I have a template in my section. I want to bind the Width of one of the values in that temp开发者_如何学编程late to the width of a control in my Main XAML section.

Can this be done? Expression Blend only shows the Template in the Binding list.

For example, this is what I am wanting to have work:

<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


Once inside the Template you're sort of isolated from other elements (with good reason - it can be reused elsewhere). In this case (assuming the template is used somewhere under "MainGrid") it looks like you can use a RelativeSource FindAncestor Binding to locate the parent Grid (you'll need to make sure to count the Grids in the VisualTree to get the right AncestorLevel - in just the code here it would be 2). The Path would be ColumnDefinitions[1].Width. Keep in mind that this depends on you maintaining the structure of the elements where you are using the template so it is a bit fragile. There is also an alternate method using SharedSizeGroup that can connect Grid Rows or Columns at different levels but that works only with Auto and fixed pixel sizes. This Binding method works with fixed and * sizes.

Entire Binding:

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


Do you mean that you want your columns to be always the same width or do you mean that at first, they are at same width? If so, why not define a style and use it from both columns?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜