这里我有一个自定义依赖属性,我以这种方式设置它。我想要做的是将自己的属性绑定到您可以在代码中看到的控件。我已经尝试过RelativeResource
,你可以在代码中看到,但没有显示任何内容。我是否需要使用ControlTemplate
to声明目标类型或有什么方法可以解决这个问题?
资源字典
<Style TargetType="{x:Type infiniteReservoir:PressureSource}">
<Setter Property="PropertyPanel">
<Setter.Value>
<ScrollViewer >
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<TextBlock Text="Pressure:" Grid.Row="0"/>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox/>
<ComboBox Grid.Column="1"/>
</Grid>
<TextBlock Text="Temperature:" Grid.Row="1"/>
<Grid Grid.Row="1" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBox/>
<ComboBox Grid.Column="1"/>
</Grid>
<TextBlock Text="Label:" Grid.Row="2"/>
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Text="Media:" Grid.Row="3"/>
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding ToolTip}"/>
<TextBlock Text="Fluid Zone ID:" Grid.Row="4"/>
<TextBlock Grid.Row="4" Grid.Column="1"/>
<TextBlock Text="Port Name:" Grid.Row="5"/>
<TextBox Grid.Row="5" Grid.Column="1"/>
</Grid>
</ScrollViewer>
</Setter.Value>
</Setter>
</Style>
模型
#region PropertyPanel
public ScrollViewer PropertyPanel
{
get { return (ScrollViewer)GetValue(PropertyPanelProperty); }
set { SetValue(PropertyPanelProperty, value); }
}
public static readonly DependencyProperty PropertyPanelProperty = DependencyProperty.Register("PropertyPanel", typeof(ScrollViewer), typeof(DesignerItem));
#endregion
任何帮助,将不胜感激。
TemplatedParent
仅适用于ControlTemplate。
我怀疑你想要的是这个:
<Grid
DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type infiniteReservoir:PressureSource}}}">
作为旁注,绑定DataContext通常被认为是不好的做法,因为这通常会产生意想不到的副作用。您可以在子项的每个绑定中使用RelativeSource:
<TextBlock Text="Label:" Grid.Row="2"/>
<TextBox
Grid.Row="2"
Grid.Column="1"
Text="{Binding Name, RelativeSource={RelativeSource AncestorType={x:Type infiniteReservoir:PressureSource}}}"
/>
<TextBlock Text="Media:" Grid.Row="3"/>
<TextBlock
Grid.Row="3"
Grid.Column="1"
Text="{Binding ToolTip, RelativeSource={RelativeSource AncestorType={x:Type infiniteReservoir:PressureSource}}}"
/>