WPF,Caliburn Micro Bind数据库记录到VM

时间:2015-08-05 10:27:03

标签: c# wpf

再次与WPF和Caliburn Micro斗争。如果记录存在,我想将DB记录绑定到视图。但是,在检索记录后,视图不会使用检索到的字段进行更新。以下是类似的代码:

查看:

<TextBox x:Name="personId" Margin="114,12,288,281" >
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="LostFocus">
                    <cal:ActionMessage MethodName="Retrieve" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
</TextBox>
<TextBox x:Name="firstName" />
<TextBox x:Name="lastName" />

视图模型:

[ImplementPropertyChanged]
internal class PersonViewModel
{
    public string personId { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }


    public void Retrieve()
    {
       try
            {
                using (var con = new SqlConnection(conStr))
                {
                    var q = con.Query<PersonViewModel>("select firstName,lastName from Person where id = @id", new {id = personId}).First();
                    MessageBox.Show("Succesfully retrieved " + q.firstName + " "  +  q.lastName);
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("error retrieving due to {0}", x.Message);
            }
    }

}

Retrieve方法正在触发,我正在MessageBox中获得结果。但是视图未更新。我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

您不清楚模型和视图模型问题的分离。 我会像这样实现你的场景:

[ImplementPropertyChanged]
public class PersonDetailsPageViewModel
{
    public Person Person { get; set; }

    public void Retrieve()
    {
       try
       {
          using (var con = new SqlConnection(conStr))
          {
              Person = con.Query<Person>("select firstName,lastName from Person where id = @id", new {id = personId}).First();
          }
       }
       catch (SqlException ex)
       {
           Console.WriteLine("error retrieving due to {0}", ex.Message);
       }
    }
}

答案 1 :(得分:0)

您的数据将从数据库中检索到q。您需要将数据复制到personIdfirstName等属性中。更新属性时,属性更改通知将更新视图。

这样的事情:

   public void Retrieve()
    {
       try
            {
                using (var con = new SqlConnection(conStr))
                {
                    var q = con.Query<PersonViewModel>("select firstName,lastName from Person where id = @id", new {id = personId}).First();
                    // Copy database data into the local properties so they will update the view...
                    this.personId = q.personId;
                    this.firstName = q.firstName;
                    ...
                    MessageBox.Show("Succesfully retrieved " + q.firstName + " "  +  q.lastName);
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("error retrieving due to {0}", x.Message);
            }
    }