[英]Silverlight TextBlock not binding to MVVM, what have I missed?
MainPage.xaml
<TextBlock Text="{Binding Pathname, Source={StaticResource ViewModel}, Mode=OneWay}" />
应用程式
<ResourceDictionary>
<vm:InspectViewModel x:Key="ViewModel" />
</ResourceDictionary>
视图模型
private string _pathname = null;
public string Pathname
{
get { return _pathname; }
set
{
if (_pathname != value)
{
_pathname = value;
RaisePropertyChanged("Pathname");
}
}
}
public void UpdatePathname(string path)
{
Pathname = path;
}
主页代码背后
private void lazyNavTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
InspectViewModel vm = new InspectViewModel();
var path = view.GetPath().ToArray();
string pathname = null;
// to figure out what the pathname is
for (int i = 0; i < path.Count(); i++)
{
TreeList treeItem = (TreeList)path[i].Key;
if (i == path.Count()-1)
pathname = pathname + treeItem.Name;
else
pathname = pathname + treeItem.Name + " : ";
}
vm.UpdatePathname(pathname);
}
绑定的TextBlock不显示任何内容(nada,zip)。 路径名shource正确更改,但是在更改时激发INotifyPropertyChanged事件时似乎什么也没发生。
我确定我确实缺少一些明显的东西,但我不知道该怎么办!
您正在创建ViewModel的2个实例:
InspectViewModel vm = new InspectViewModel()
,这是修改后的实例) 您应该使用ViewModel的单个实例,例如,
var vm = (InspectViewModel)Application.Current.Resources["ViewModel"];
而不是在MainPage后台代码中创建它。
这是因为每次在lazyNavTree_SelectedItemChanged中都从视图模型创建一个实例。 您只能使用一个。
看起来您只是在绑定中错过了Path ,请尝试;
Text="{Binding Path=Pathname, Source={StaticResource ViewModel}, Mode=OneWay}"
编辑:显然这不是问题所在,但保留此答案,因为xhedgepigx在下面提供了一个有用的链接作为注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.