简体   繁体   English

对UserControl中的绑定感到困惑

[英]Confused about Binding in UserControl

I'm creating a UserControl object, and i'm trying to assign values using Binding (with PropertyChanged). 我正在创建一个UserControl对象,我正在尝试使用Binding(使用PropertyChanged)分配值。 I made a prototype, when I assign value in ViewModel , the value does not appear or modify the UserControl component, but if I assign the value directly in the UserControl object that is in view, the modification works. 我创建了一个原型,当我在ViewModel中赋值时,该值不会出现或修改UserControl组件,但如果我直接在视图中的UserControl对象中赋值,则修改有效。 I would like to understand what I'm doing wrong, since works fine if i just add an object on my window and binding directly (again, using PropertyChanged). 我想了解我做错了什么,因为如果我只是在我的窗口上添加一个对象并直接绑定(再次使用PropertyChanged),我的工作正常。 Follow the code below. 请遵循以下代码。

Thanks for any help. 谢谢你的帮助。

Best Regards, 最好的祝福,

Gustavo. 古斯塔沃。

UserControl: 用户控件:

<UserControl x:Class="WpfControlLibrary1.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="30" d:DesignWidth="300">
<Grid>
    <TextBlock Text="{Binding Title}" />
</Grid>
</UserControl>

Code Behind of User Control: 用户控制的代码:

    public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    #region Title Property

    public static String GetTitle(DependencyObject obj)
    {
        return (String)obj.GetValue(TitleProperty);
    }

    public static void SetTitle(DependencyObject obj, String value)
    {
        obj.SetValue(TitleProperty, value);
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.RegisterAttached(
            "Title",
            typeof(String),
            typeof(UserControl1),
            new FrameworkPropertyMetadata(TitleChangedCallback)
            );

    private static void TitleChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UserControl1 _this = (d as UserControl1);
    }

    private String title;
    public String Title
    {
        get { return title; }
        set
        {
            title = value;
            OnPropertyChanged("Title");
        }
    }

    #endregion

    #region INotifyPropertyChanged event and method

    public event PropertyChangedEventHandler PropertyChanged;

    // Create the OnPropertyChanged method to raise the event 
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    #endregion

** My Window: ** **我的窗口:**

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:uc="clr-namespace:WpfControlLibrary1;assembly=WpfControlLibrary1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <uc:UserControl1 Title="{Binding TitleVM, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>

** My Code-Behind/ViewModel: ** **我的Code-Behind / ViewModel:**

public partial class MainWindow : INotifyPropertyChanged
{
    // Notify WPF that Counter changed
    public event PropertyChangedEventHandler PropertyChanged;

    public MainWindow()
    {
        InitializeComponent();

        TitleVM = "açsldkfjasçldkfj";
    }

    private String titleVM;
    public String TitleVM
    {
        get { return titleVM; }
        set
        {
            titleVM = value;
            OnPropertyChanged("TitleVM");
        }
    }

    // Create the OnPropertyChanged method to raise the event 
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

}

Your Window doesnt have a DataContext . 您的Window没有DataContext Bindings cannot be resolved. 绑定无法解决。

Try this: 尝试这个:

public MainWindow()
{
    InitializeComponent();

    DataContext = this; //This is what you're missing!

    TitleVM = "açsldkfjasçldkfj";
}

Edit: 编辑:

You're also missing the same thing in the UserControl 你在UserControl也缺少同样的东西

public UserControl1()
{
    InitializeComponent();
    DataContext = this;
}

With help of HighCore, i've found one problem, and the other problem was my UserControl doesn't have a name defined. 在HighCore的帮助下,我发现了一个问题,另一个问题是我的UserControl没有定义名称。

Just put: 刚刚放:

x:Name="UserControl"

Into XAML of UserControl and will work. 进入UserControl的XAML并将工作。 Also, i've modified my code behind to this: 另外,我已将我的代码修改为:

        public String Title
    {
        get { return (String)base.GetValue(TitleProperty); }
        set { base.SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
     DependencyProperty.RegisterAttached(
         "Title",
         typeof(String),
         typeof(UserControl1),
         new FrameworkPropertyMetadata(null)
         );

A clean code to our eyes. 一个干净的代码给我们的眼睛。

PS: There's no need to put: PS:没有必要放:

DataContext = this;

On Code Behind of UserControl. 关于UserControl的代码背后。 At least here only result on bug, no values was comming. 至少在这里只会导致bug,没有值出现。

Thanks HighCore for you help. 感谢HighCore为您提供帮助。

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

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