【发布时间】:2014-11-21 13:14:08
【问题描述】:
我完全迷失了依赖对象和绑定。我经常在不了解原因和方式的情况下让事情正常进行,这个问题是关于知道应该发生什么。
我有一个带有以下 XAML 的小型用户控件
<Grid>
<Image Source="{Binding Icon}"></Image>
<TextBlock Text="{Binding Title}"></TextBlock>
</Grid>
我的代码后面有以下内容
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof(Image), typeof(MenuItem));
public Image Icon
{
get { return (Image)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(String), typeof(MenuItem));
public string Title
{
get { return (string)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
我的 MainWindow 是空的,除了对该控件和 ResourceDictionary 的引用。在后面的MainWindow代码中,我在构造函数中设置了DataContext。
<Window x:Class="AppUi.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:AppUi.Control"
Title="">
//set up to Resource Dictionary - all binding and styling works fine :)
<loc:MenuItem Icon="{Binding MailIcon}" Title="{Binding MailTitle}"></loc:MenuItem>
在 MainWindow 的 ModelView 中,我有以下 2 个属性
private Image_mailIcon;
public Image MailIcon{
//inotifyproperty implementation
}
private string _mailTitle;
public string MailTitle{
//inotifyproperty implementation
}
我的问题是,在 UserControl 中,我该如何进行绑定?由于它是 MainWindow 中的用户控件,并且 MainWindow 已经有一个 datacontext,我认为 UserControl 将从父级继承 DataContext(根据我的阅读)。
那么,在我的 UserControl XAML 中,我应该绑定到 MainWindow 的代码隐藏属性还是绑定到 ViewModel 属性?
换句话说,我的 UserControl 应该是
<Grid>
<Image Source="{Binding MailIcon}"></Image>
<TextBlock Text="{Binding MailTitle}"></TextBlock>
</Grid>
或
<Grid>
<Image Source="{Binding Icon}"></Image>
<TextBlock Text="{Binding Title}"></TextBlock>
</Grid>
或者,因为我使用的是 DataContext 并且 UserControl 继承,我什至需要依赖属性吗?
【问题讨论】:
标签: wpf xaml mvvm user-controls