【问题标题】:Error Binding a property of a user control wp7绑定用户控件wp7的属性时出错
【发布时间】:2023-03-11 11:07:01
【问题描述】:

我创建了一个用户控件以在应用程序周围的多个地方使用它,该控件有两个属性,女巫值绑定到视图模型。问题是当应用程序加载时它会在设置用户控件的属性之一时引发异常,知道吗?

用户控件.xaml

<UserControl x:Class="Client.Controls.CredentialsUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480">

    <Grid Name="LayoutRoot">

        <TextBlock Text="{Binding Title}" Margin="12,20,12,390" TextWrapping="Wrap" FontSize="30"/>

        <TextBlock Text="Username" Margin="39,88,260,362" FontSize="25"/>
        <TextBlock Text="{Binding Credentials.User}" Margin="361,88,0,362" FontSize="25" />

        <TextBlock Text="Password" Margin="39,148,260,302" FontSize="25"/>
        <TextBlock Text="{Binding Credentials.Password}" Margin="361,148,0,302" FontSize="25" />

</UserControl>

UserControl.xaml.cs

public partial class CredentialUserControl: UserControl , INotifyPropertyChanged 
{

    public const string CredentialsPropertyName = "Credentials";

    private ICredentials _credentials= null;
    public ICredentials Credentials
    {
        get
        {
            _credentials_report;
        }

        set
        {
            if (_credentials== value)
            {
                return;
            }

            _credentials= value;
            NotifyPropertyChanged(CredentialsPropertyName );
        }
    }

    public string Title { get; set; }



    public MobfoxReportUserControl()
    {
        InitializeComponent();

        Loaded += PageLoaded;
    }

    void PageLoaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = this;

    }


    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string prop)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}

用法:

<Controls:CredentialsUserControl  Title="Your Credentials" Credentials="{Binding CurrentUser}"/>

ViewModel 属性 sn-p 与 UserControl.xaml.cs 中显示的相同

抛出的异常

System.Windows.Markup.XamlParseException occurred
  Message=Set property 'CredentialsUserControl.Credentials' threw an exception. [Line: 29 Position: 85]
  InnerException: System.ArgumentException
       Message=ArgumentException
       StackTrace:
            at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
            at System.Reflection.RuntimePropertyInfo.InternalSetValue(PropertyInfo thisProperty, Object obj, Object value, Object[] index, StackCrawlMark& stackMark)
            at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)

我发现异常的根源是 MainPage 上的绑定,但并没有真正理解导致它的原因或原因。

谢谢

【问题讨论】:

  • this.DataContext = this; 那是什么?请从构造函数中删除LayoutRoot.DataContext = this;this.DataContext = this;
  • @Ku6opr - 你比我先到!绝对“闻起来”不对
  • 编辑代码但问题依旧XD
  • this.DataContext = Credentials;不是this.DataContext = this;
  • @Ku6opr 这没有任何意义,请注意我在用户控件中有两个属性,我正在使用它们来绑定。

标签: wpf windows-phone-7 xaml binding user-controls


【解决方案1】:

通过在用户控件中显式设置DataContext,您将丢失它。此外,您应该使用DependencyProperty。最后,您的 XAML 加载了精确的边距...您可能想要切换到使用网格行/列定义,就像您需要更改页面一样,这会更容易。

using System.Net;
using System.Windows;
using System.Windows.Controls;

namespace Client.Controls
{
    public partial class CredentialsUserControl : UserControl
    {
        public CredentialsUserControl()
        {
            InitializeComponent();

            if (System.ComponentModel.DesignerProperties.IsInDesignTool)
            {
                Credentials = new NetworkCredential("user","pass");
                Title = "testing creds";
            }
        }



        public ICredentials Credentials
        {
            get { return (ICredentials)GetValue(CredentialsProperty); }
            set { SetValue(CredentialsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Credentials.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CredentialsProperty =
            DependencyProperty.Register("Credentials", typeof(ICredentials), typeof(CredentialsUserControl),new PropertyMetadata(null));

        public string Title { get; set; }

    }
}

<Grid Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBlock Text="{Binding ElementName=control, Path=Title}" TextWrapping="Wrap" FontSize="30" Margin="12,24" />

    <Grid Grid.Row="1" Margin="40,0,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="12" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBlock Text="Username" FontSize="25" Grid.Column="0" />
        <TextBlock Text="{Binding ElementName=control, Path=Credentials.User}" FontSize="25" Grid.Column="1" HorizontalAlignment="Right"/>

        <TextBlock Text="Password" Grid.Row="2" FontSize="25" Grid.Column="0" />
        <TextBlock Text="{Binding ElementName=control, Path=Credentials.Password}" Grid.Row="2" FontSize="25" Grid.Column="1" HorizontalAlignment="Right"/>
    </Grid>
</Grid>

【讨论】:

  • 我已经注意到了,非常感谢您的回复;)。顺便说一句,你的网格建议太棒了 xDD
【解决方案2】:

我不确定,但构造函数中的这段代码是什么:

    LayoutRoot.DataContext = this;
    this.DataContext = this;

看起来很“危险”……

【讨论】:

  • 不是问题,我的原始代码现已更新。即使在加载的事件上设置了上下文,问题仍然存在。
  • 我想您的视图模型/数据上下文确实为 CurrentUser 提供了 ICredentials?
  • 是的,如果我将 usercontrol xaml 代码放到主页中,一切正常,所以没有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 2016-09-09
  • 2012-07-18
相关资源
最近更新 更多