You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF自定义UserControl设计器显示正常但运行时不显示问题求助

问题分析与解决方案

核心问题

你的自定义ButtonGame控件存在两个关键错误,导致运行时绑定失效:

  1. 依赖属性注册名称与CLR属性名不匹配:注册依赖属性时用了"Content"作为名称,但CLR属性是Label,WPF依赖属性系统依赖名称匹配来关联属性,这会导致绑定找不到正确的属性源。
  2. XAML中使用了错误的属性名:在Window的XAML里你用了Content="DeS",但自定义控件的绑定目标是Label属性,而非UserControl自带的Content属性。

修复步骤

1. 修正依赖属性注册代码

修改ButtonGame的C#代码,将依赖属性的注册名称改为"Label",与CLR属性名一致:

public String Label {
    get { return (String)GetValue(LabelProperty); }
    set { SetValue(LabelProperty, value); }
}
public static readonly DependencyProperty LabelProperty =
  DependencyProperty.Register(
      "Label",  // 这里从"Content"改为"Label"
      typeof(string),
      typeof(ButtonGame));

2. 修正Window中的XAML声明

将Window里的Content="DeS"替换为Label="DeS",匹配自定义控件的属性:

<local:ButtonGame Label="DeS" Grid.Column="0"/>
<local:ButtonGame Label="DS1" Grid.Column="1"/>
<local:ButtonGame Label="DS2" Grid.Column="2"/>
<local:ButtonGame Label="DS3" Grid.Column="3"/>
<local:ButtonGame Label="BB" Grid.Column="4"/>
<local:ButtonGame Label="SE" Grid.Column="5"/>
<local:ButtonGame Label="ER" Grid.Column="6"/>

3. 可选优化:将Source改为依赖属性

当前Source是普通CLR属性,无法支持绑定或样式设置,建议也改为依赖属性,增强控件灵活性:

public ImageSource Source {
    get { return (ImageSource)GetValue(SourceProperty); }
    set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty SourceProperty =
    DependencyProperty.Register(
        "Source",
        typeof(ImageSource),
        typeof(ButtonGame),
        new PropertyMetadata(null, OnSourceChanged));

private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    var control = d as ButtonGame;
    control.Background.Source = e.NewValue as ImageSource;
}

这样就可以在XAML中直接设置Source="/DeS/ButtonNormal.png",而不需要依赖样式对Image的设置。

验证修改

完成上述修改后,运行程序时XAML中声明的ButtonGame控件应该能正确渲染Label内容,和设计器预览效果一致。

内容的提问来源于stack exchange,提问作者Fran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 14:41:01