例如说我有以下类型:
public class Site
{
public string Name { get; set; }
public int SiteId { get; set; }
public bool IsLocal { get; set; }
}
上面的类型可以分配到 ViewModel 中的 Propety 中,就像假设已经创建了相应的支持字段但这里省略了 ofc 一样:
public Site SelectedSite
{
get { return _selectedSite; }
set
{
_selectedSite = value;
// raise property changed etc
}
}
在我的 xaml 中,直接绑定(bind)将是:
<TextBlock x:Name="StatusMessageTextBlock"
Width="Auto"
Height="Auto"
Style="{StaticResource StatusMessageboxTextStyle}"
Text="{Binding MessageToDisplay,
Mode=OneWay,
UpdateSourceTrigger=PropertyChanged}" />
您可以使用点符号语法扩展绑定(bind)吗?例如:
<TextBlock x:Name="StatusMessageTextBlock"
Width="Auto"
Height="Auto"
Style="{StaticResource StatusMessageboxTextStyle}"
**Text="{Binding SelectedSite.Name,**
Mode=OneWay,
UpdateSourceTrigger=PropertyChanged}" />
似乎是一个有趣的功能,但我的直觉是否定的,因为我的 DC 是在运行时分配的,所以在设计时或编译时,我看不出任何可以使这个功能起作用的线索?
如果误解了复杂对象是什么,请纠正我,为了这个问题,我已经简化了我的。
最佳答案
当然这是可能的。但是,WPF 需要知道路径上的任何属性何时发生更改。为此,您需要实现 INotifyPropertyChanged
(或其他支持的机制)。在您的示例中,Site
以及包含 SelectedSite
的 VM应实现变更通知)。
以下是如何实现您在问题中指定的功能:
// 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);
}
}
}
}
您的 View 可能看起来像这样(假设
DataContext
类型为 SitesViewModel
):<ListBox ItemsSource="{Binding Sites}" SelectedItem="{Binding SelectedSite}"/>
关于wpf - 从 View 绑定(bind)到 ViewModel 中的复杂对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231749/