簡體   English   中英

WPF用戶控件屬性未綁定或更新

[英]WPF user control properties not binding or updating

我在弄亂WPF並創建用戶控件,但是很難理解數據綁定應該如何工作。 數據綁定似乎過於復雜,只要WPF失效,我認為MS會創建一些快捷方式來避免進行大量的樣板代碼。

用戶控件xaml

<UserControl x:Class="WPFTest.FancyBox"
             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">
   <DockPanel>
      <Label Content="{Binding MyText}"></Label>
   </DockPanel>
</UserControl>

用戶控件.cs

public partial class FancyBox : UserControl
{
    public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText", typeof(string), typeof(FancyBox), new PropertyMetadata(null));

    public string MyText
    {
        get => (string)GetValue(MyTextProperty);
        set => SetValue(MyTextProperty, value);
    }

    public FancyBox()
    {
        InitializeComponent();
    }
}

我主窗口中的用法

<StackPanel>
    <local:FancyBox MyText="testing!"/>
</StackPanel>

綁定Content="{Binding MyText}"綁定到控件(Label)的DataContext ,該控件從樹的最接近祖先繼承,該祖先擁有一個(您的代碼未顯示任何DataContext分配)

您的預期行為是將Label的Content綁定到User Control的Property,在這種情況下,您需要讓用戶控制您的源代碼。 例如,有很多方法可以做到這一點:

<UserControl x:Class="WPFTest.FancyBox"
x:Name="RootElement"
....
<Label Content="{Binding MyText, Source={x:Reference RootElement} />

或另一種方式:

<Label Content="{Binding MyText, RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type local:FancyBox}}" />

請記住,沒有源(Source,RelativeSource)的任何綁定都將來自DataContext

我想我根本不需要數據綁定

我將控件標簽更改為:

<Label x:Name="lblText"></Label>

和我的代碼背后:

public string MyText
{
     get => lblText.Content.ToString();
     set => lblText.Content = value;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM