繁体   English   中英

WPF UserControl依赖项属性值

[英]WPF UserControl Dependency Property value

我有以下问题:我在WPF中制作了一个具有AgreementID属性的UserControl。 我需要在另一个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));

这是XAML,我将其称为先前的UserControl:

 <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。 因此,我在绑定中获得了正确的值,但是并没有传递正确的值。

希望我的问题对您有所了解,如果需要,可以提供其他信息!

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM