簡體   English   中英

綁定UserControl中的文本框

[英]Bind Textbox in UserControl

我的觀點

<UserControl x:Class="Views.PartView"
             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"
             xmlns:viewModels="clr-namespace:EComponents.ViewModels"
             mc:Ignorable="d" 
             x:Name="PartUc"
             d:DataContext="{d:DesignInstance viewModels:PartViewModel}">        
        <Grid>
            <TextBox x:Name="NameTb" Text="{Binding Name}" />
       </Grid>
</UserControl>

我的ViewModel

public class PartViewModel : ViewModel<Part>
{
    public PartViewModel(Part model) : base(model)
    {
        PartListViewModel.OnSelectedPartChanged += PartListViewModel_OnSelectedPartChanged;
    }    
    void PartListViewModel_OnSelectedPartChanged(Part p)
    {
        Model = Part.GetPart(p);
    }      
    public string Name
    {
        get
        {
            return Model.Name;
        }
        set
        {
            if (Name != value)
            {
                Model.Name = value;
                this.OnPropertyChanged("Name");
            }
        }
    }   
}

我的模特

public class Part
{
    public string Name { get; set; }
}

我不知道為什么,但是即使調用此行,但UserControl中的TextBox仍未填充零件的Name屬性

Model = Part.GetPart(p);

我這樣設置我的視圖的DataContent

public partial class PartView : UserControl
{
    public PartView()
    {
        InitializeComponent();
        DataContext = new PartViewModel(new Part());
    }
}

似乎在PartListViewModel_OnSelectedPartChanged更改Model時,您不通知UI。 您需要為每個與Model相關的屬性更改后調用this.OnPropertyChanged(...) ,或使用null參數this.OnPropertyChanged(null)進行調用以刷新所有屬性

void PartListViewModel_OnSelectedPartChanged(Part p)
{
    Model = Part.GetPart(p);
    this.OnPropertyChanged(null);
} 

您的代碼中有一個小問題:

        if (Name != value)
        {
            Model.Name = value;
            this.OnPropertyChanged("Name");
        }

應該:

        if (Model.Name != value)
        {
            Model.Name = value;
            this.OnPropertyChanged("Name");
        }

自引用視圖模型的Name屬性會給您帶來問題。

最后但並非最不重要的一點是,您需要在代碼背后添加代碼以在運行時綁定DataContext。

編輯

我只是再次查看了您的代碼以及對該問題的評論。 在事件處理程序中設置Model的值時,還需要在其中設置DataContext。 更改模型引用不會更新DataContext。

暫無
暫無

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

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