【问题标题】:WPF UserControl Dependency Property valueWPF 用户控件依赖属性值
【发布时间】:2011-10-14 14:03:33
【问题描述】:

我有以下问题:我在 WPF 中创建了一个 UserControl,它有一个 AgreementID 属性。我需要在另一个 UserControl 中调用这个 UserControl,并且我需要在调用它时给它一个 AgreementID。现在我在第一个 UserControl 中做了一个 DependencyProperty,但它不起作用。

这是我的第一个 UserControl 的代码:

public partial class UC1001_AgreementDetails_View : UserControl
    {

        private UC1001_ActiveAgreementContract _contract;
        private int _agreementID;

        public int AgreementID
        {
            get { return _agreementID; }
            set { _agreementID = value; }
        }

        public UC1001_AgreementDetails_View()
        {
            InitializeComponent();
        }

       public static readonly DependencyProperty AgreementIDProperty = DependencyProperty.Register("AgreementID", typeof(int), typeof(UC1001_AgreementDetails_View), new PropertyMetadata(null));

这是我调用前一个 UserControl 的 XAML:

 <DataGridTextColumn.ElementStyle>
            <Style TargetType="{x:Type TextBlock}">
            <!--<Setter Property="Text" Value="{Binding Months[9].AgreementID}"/>-->
            <Setter Property="Tag" Value="{Binding Months[9].AgreementID}"/>
            <Setter Property="Background" Value="White" />
            <Setter Property="DataGridCell.ToolTip">
                 <Setter.Value>
                     <my:UC1001_AgreementDetails_View Background="#FFF" Opacity="0.88" AgreementID="{Binding Months[9].AgreementID}"/>
                 </Setter.Value>
            </Setter>

所以我想将该月的AgreementID传递到第一个UserControl,但是当我检查它时,传递的值总是0,但它应该是3。我检查了Months[9].AgreementID的值,它是3确实。所以我在绑定中得到了正确的值,但它没有通过正确的传递。

希望我的问题对你来说有点清楚,如果需要可以提供更多信息!

【问题讨论】:

  • 看看MVVM;这将允许您将数据存储在可以在您的视图(用户控件)之间共享的通用视图模型中。更多的时候不是 UserControl 是 WinForms 思维的遗留物。

标签: c# wpf xaml dependency-properties


【解决方案1】:

您为依赖属性定义了错误的属性外观。在您的属性定义中,您需要处理 Dependency Property 并设置并返回其值:

public int AgreementID
{
    get { return (int) GetValue(AgreementIDProperty ); }
    set { SetValue(AgreementIDProperty, value); }
}

【讨论】:

    【解决方案2】:

    如前所述,您的属性包装器应该在依赖属性上调用GetValueSetValue(并且您可以省去支持字段)。但是,值得指出的是,当 DependencyProperty 直接在 XAML 中设置或从声明性 Binding 设置时,包装器属性将被绕过。因此,如果您实际上使用GetValue 检查了DependencyProperty 本身的值,那么您会看到该值实际上是由您的Binding 设置的。这是通过程序代码中的包装器检索属性值失败,因为它没有访问DependencyProperty

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2014-10-09
      • 1970-01-01
      • 2021-05-14
      相关资源
      最近更新 更多