c# - UserControl 依赖属性设计时

标签 c# wpf binding dependency-properties

我正在 WPF 中创建一个简单的用户控件,它在 Button 中包含一个 TextBlock。

<UserControl x:Class="WpfExpansion.MyButton"..... >
    <Grid >
        <Button Background="Transparent" >
            <TextBlock Text="{Binding Path=Text}"/>
        </Button>
    </Grid>
</UserControl>

还有“文本”依赖属性。

public partial class MyButton : UserControl
{
    public MyButton()
    {
        InitializeComponent();
        this.DataContext = this;         
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(MyButton), new PropertyMetadata(string.Empty));

}

然后我像这样使用 UserControl:

<MyButton Text="Test" />

问题是 Visual Studio 设计没有改变,但它在运行时有效。

怎么了?

我也试过

DataContext="{Binding RelativeSource={RelativeSource Self}}"

在 UC 定义中,没有成功。

最佳答案

尝试使用 FrameworkPropertyMetadata 而不是 PropertyMetadata,如下所示指定 AffectsRender,然后重新启动 Visual Studio:

public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string), typeof(MyButton),
        new FrameworkPropertyMetadata(string.Empty,
            FrameworkPropertyMetadataOptions.AffectsRender));

MSDN Documentation关于 FrameworkPropertyMetadataOptions.AffectsRender

Some aspect of rendering or layout composition (other than measure or arrange) is affected by value changes to this dependency property.

对于其他情况,有 AffectsMeasure、AffectsArrange 等选项。

关于c# - UserControl 依赖属性设计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18158500/

相关文章:

combobox - OpenUI5 : Binding sap. m.ComboBox 到 sap.ui.table.Table 中的 JSONModel() 列

c# - 如何判断代码是否不能进一步优化

c# - 在 WPF 中拖放文件不起作用

wpf - 您可以使用 LiveCharts 显示带有 x 和 y 值对的线系列吗?

c# - DataGridColumn 与动态生成的数据绑定(bind)

JSF:如何绑定(bind)许多 h:selectBooleanCheckbox?

c# - 我们需要企业库日志来抛出错误

c# - 如何在WPF中选择日期和时间

c# - 如何使用 async/await 异步创建 DispatcherObject?

c# - 无法使转换器工作