Ibr*_*taz 4 data-binding wpf mvvm complextype c#-4.0
比方说,我有以下类型:
public class Site
{
public string Name { get; set; }
public int SiteId { get; set; }
public bool IsLocal { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
可以将上述类型分配为在ViewModel中的Propety中保存,如果假定已创建相应的后备字段但在此处省略了ofc:
public Site SelectedSite
{
get { return _selectedSite; }
set
{
_selectedSite = value;
// raise property changed etc
}
}
Run Code Online (Sandbox Code Playgroud)
在我的xaml中,直接绑定将是:
<TextBlock x:Name="StatusMessageTextBlock"
Width="Auto"
Height="Auto"
Style="{StaticResource StatusMessageboxTextStyle}"
Text="{Binding MessageToDisplay,
Mode=OneWay,
UpdateSourceTrigger=PropertyChanged}" />
Run Code Online (Sandbox Code Playgroud)
您可以使用点表示法语法扩展绑定吗?例如:
<TextBlock x:Name="StatusMessageTextBlock"
Width="Auto"
Height="Auto"
Style="{StaticResource StatusMessageboxTextStyle}"
**Text="{Binding SelectedSite.Name,**
Mode=OneWay,
UpdateSourceTrigger=PropertyChanged}" />
Run Code Online (Sandbox Code Playgroud)
看起来像一个有趣的功能,但我的直觉是不,因为我的DC在RunTime分配,所以在DesignTime或CompileTime,我看不到任何可以使这个功能工作的线索?
纠正我,如果误解了复杂的物体是什么,为了这个问题我已经简化了我的想法.
当然这是可能的.但是,WPF需要知道路径上的任何属性何时发生了变化.为此,您需要实现INotifyPropertyChanged
(或其他支持的机制).在您的示例中,两者Site
和包含的VM SelectedSite
都应实现更改通知).
以下是如何实现您在问题中指定的功能:
// simple DTO
public class Site
{
public string Name { get; set; }
public int SiteId { get; set; }
public bool IsLocal { get; set; }
}
// base class for view models
public abstract class ViewModel
{
// see http://kentb.blogspot.co.uk/2009/04/mvvm-infrastructure-viewmodel.html for an example
}
public class SiteViewModel : ViewModel
{
private readonly Site site;
public SiteViewModel(Site site)
{
this.site = site;
}
// this is what your view binds to
public string Name
{
get { return this.site.Name; }
set
{
if (this.site.Name != value)
{
this.site.Name = value;
this.OnPropertyChanged(() => this.Name);
}
}
}
// other properties
}
public class SitesViewModel : ViewModel
{
private readonly ICollection<SiteViewModel> sites;
private SiteViewModel selectedSite;
public SitesViewModel()
{
this.sites = ...;
}
public ICollection<SiteViewModel> Sites
{
get { return this.sites; }
}
public SiteViewModel SelectedSite
{
get { return this.selectedSite; }
set
{
if (this.selectedSite != value)
{
this.selectedSite = value;
this.OnPropertyChanged(() => this.SelectedSite);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的视图可能看起来像这样(假设DataContext
类型SitesViewModel
):
<ListBox ItemsSource="{Binding Sites}" SelectedItem="{Binding SelectedSite}"/>
Run Code Online (Sandbox Code Playgroud)