我一直在尝试使用 WPF 并使用 CustomControl 制作了我自己的面板类型,因此我可以使我的所有面板看起来像一个带有背景、圆角等的框。
我没有遇到的麻烦是我想在运行时更改使用 TemplateBinding 绑定的项目的属性。
我的问题是通过代码更改它不起作用。
希望有人能发现我的错误并告诉我我在哪里有点密集。
这会找到 contentControl 并更改值,这只是从未出现在应用程序中,就好像绑定未激活一样。
希望有人可以提供帮助。
控制模板。
<ControlTemplate x:Key="ContentBoxControlTemplate" TargetType="{x:Type local:ContentBox}"><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.124*"/>
<RowDefinition Height="0.876*"/>
</Grid.RowDefinitions>
<Border BorderBrush="Black" BorderThickness="0" HorizontalAlignment="Stretch" Height="Auto" VerticalAlignment="Stretch" CornerRadius="20" Grid.RowSpan="2" Style="{TemplateBinding Style}" />
<Rectangle HorizontalAlignment="Stretch" Height="Auto" RadiusY="0" StrokeThickness="0" VerticalAlignment="Stretch" Width="Auto" Margin="10,0,10,20" Fill="White" Grid.Row="1"/>
<Rectangle Fill="{DynamicResource TopInnerShadow}" HorizontalAlignment="Stretch" Height="Auto" RadiusY="0" StrokeThickness="0" VerticalAlignment="Stretch" Width="Auto" Margin="10,0,10,20" Grid.Row="1"/>
<Rectangle Fill="{DynamicResource RightInnerShadow}" HorizontalAlignment="Stretch" Height="Auto" RadiusY="0" StrokeThickness="0" VerticalAlignment="Stretch" Width="Auto" Margin="10,0,10,20" Grid.Row="1"/>
<TextBlock Grid.Row="0" x:Name="txtBoxHeading" HorizontalAlignment="Stretch" TextWrapping="Wrap" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title}" VerticalAlignment="Stretch" d:LayoutOverrides="Width, Height" Foreground="White" FontSize="36" FontFamily="Arial" Margin="20,5"/>
<Grid Grid.Row="1">
<ContentControl Content="{TemplateBinding Content}" Margin="10,0,10,20"/>
</Grid>
</Grid>
</ControlTemplate>
内容控件
public class ContentBox : ContentControl
{
static ContentBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ContentBox), new FrameworkPropertyMetadata(typeof(ContentBox)));
}
private string _title = "";
public string Title
{
get { return _title; }
set { _title = value; }
}
// Dependency Property
public static DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ContentBox), new FrameworkPropertyMetadata("Title"));
}
使用内容控件的 xml
最后是更改属性的代码
(this.Parent as ContentBox).Title = "Campaign: " + campaigns[0].Name;