2

私はこのようなC#クラスを持っています:

public partial class MyClass: UserControl
{
    public String SomeText{get;set;}
    ...

    public MyClass(String Text)
    {
        this.InitializeComponent();
        SomeText = Text;
    }

}

SomeTextそして、XAMLファイルで属性を取得したいと思います。このようなことをする方法は?

<TextBlock Text="{THIS IS HERE I WANT TO HAVE SomeText}"></TextBlock>

私はC#を初めて使用するので、方法がわかりません。簡単な方法があるはずですか?

4

2 に答える 2

3

次の例のように、UserControl要素aNameを指定して、それにバインドします。テキストが変更されない場合は、を呼び出す前にInitialiseComponentテキストを定義する必要があります。

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             x:Name="root">
    <Grid>
        <TextBlock Text="{Binding SomeText,ElementName=root}"/>
    </Grid>
</UserControl>

変更される可能性がある場合は、単純な古いプロパティではなく、SomeTextそれを宣言する必要があります。これは次のようになります。DependencyPropertystring

    public string SomeText
    {
        get { return (string)GetValue(SomeTextProperty); }
        set { SetValue(SomeTextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SomeText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SomeTextProperty =
        DependencyProperty.Register("SomeText", typeof(string), typeof(UserControl1), new UIPropertyMetadata(""));

次に、バインディングを次のように変更する必要があります。これにより、の値を変更するとUIが更新されますSomeString

<TextBlock Text="{Binding SomeText,ElementName=root,UpdateSourceTrigger=PropertyChanged}"/>
于 2012-12-06T16:23:15.253 に答える
1

まず第一に、訂正:

つまり、Property(MSDN)ではなくAttribute (MSDN)であり、これらは2つの完全に異なる概念です。

2番:

DependencyProperties WPFには(MSDN)と呼ばれる概念があり、WPFで複雑なカスタムUIコントロールを構築するために活用する必要があります。

第3:

UIでプロパティを宣言する必要がない場合があります。WPFを使用すると、強力なDataBindingエンジンMVVMパターンを介してUIをデータから分離できます。したがって、宣言しているこのコントロールが文字列プロパティを宣言するのに適切な場所であるかどうかをもう一度考えてください。

WPFで作業する場合は、これらすべての概念に精通することをお勧めします。

あなたがやろうとしていることについてもっと詳しく教えてください。私はあなたにもっと洞察を与えることができます。

編集:

基本的に、あなたがする必要があるのはDependencyProperty、あなたのコントロールで次のように宣言することです:

public static readonly DependencyProperty DisplayNameProperty = DependencyProperty.Register("DisplayName", typeof(string), typeof(mycontrol));

public string DisplayName
{
    get { return GetValue(DisplayNameProperty).ToString(); }
    set { SetValue(DisplayNameProperty, value); }
}

次に、XAMLでは:

<TextBlock Text="{Binding DisplayName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}"/>

WPFには他のフレームワークとはまったく異なる考え方が必要であることに注意してください。したがって、WPFで真剣に作業することを計画している場合は、MVVMとデータバインディングに精通することをお勧めします。

于 2012-12-06T16:23:06.553 に答える