سؤال

عند تطوير WPF UserControls، ما هي أفضل طريقة لكشف DependencyProperty لعنصر تحكم تابع باعتباره DependencyProperty لـ UserControl؟يوضح المثال التالي كيف أقوم حاليًا بكشف خاصية النص الخاصة بـ TextBox داخل UserControl.بالتأكيد هناك طريقة أفضل/أبسط لتحقيق ذلك؟

<UserControl x:Class="WpfApplication3.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Background="LightCyan">
        <TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
    </StackPanel>
</UserControl>


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

namespace WpfApplication3
{
    public partial class UserControl1 : UserControl
    {
        public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
        public string Text
        {
            get { return GetValue(TextProperty) as string; }
            set { SetValue(TextProperty, value); }
        }

        public UserControl1() { InitializeComponent(); }
    }
}
هل كانت مفيدة؟

المحلول

هذه هي الطريقة التي نقوم بها في فريقنا، بدون البحث عن RelativeSource، بل عن طريق تسمية UserControl والإشارة إلى الخصائص باسم UserControl.

<UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Background="LightCyan">
        <TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" />
    </StackPanel>
</UserControl>

في بعض الأحيان وجدنا أنفسنا نصنع أشياء كثيرة جدًا من UserControl، وكثيرًا ما قمنا بتقليص استخدامنا.سأتبع أيضًا تقليد تسمية أشياء مثل مربع النص هذا على غرار PART_TextDisplay أو شيء من هذا القبيل، بحيث يمكنك في المستقبل تصميمه مع الاحتفاظ بالرمز خلفه كما هو.

نصائح أخرى

يمكنك تعيين DataContext على هذا في مُنشئ UserControl، ثم ربطه بالمسار فقط.

خدمات العملاء:

DataContext = this;

XAML:

<TextBox Margin="8" Text="{Binding Text} />
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top