我是MVVM的新手,有问题 [英] I am new to MVVM and having a problem
问题描述
我是MVVM的新手,有一个问题,我有一个要在其他用户控件中使用的用户控件(视图).
TextBoxView.xaml
I am new to MVVM and having a problem, I have a user control (view) that I would like to use in other user controls.
TextBoxView.xaml
<UserControl x:Class="SwTest.View.TextBoxView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:SwTest.ViewModel"
mc:Ignorable="d" >
<UserControl.DataContext>
<vm:TextBoxViewModel />
</UserControl.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110" />
<ColumnDefinition Width="350" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding TxtLabel}" />
<TextBox Grid.Column="1" Text="{Binding EdtText}" />
</Grid>
</UserControl>
TestScreenView.xaml
TestScreenView.xaml
<UserControl x:Class="SwTest.View.TestScreenView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:v="clr-namespace:SwTest.View"
xmlns:vm="clr-namespace:SwTest.ViewModel"
mc:Ignorable="d" >
<UserControl.DataContext>
<vm:TestScreenViewModel />
</UserControl.DataContext>
<Grid>
<v:TextBoxView TxtLabel="Label 1" />
<v:TextBoxView TxtLabel="Label 2" />
</Grid>
</UserControl>
找不到属性TxtLabel,我使用的是MVVM灯.我已经使用依赖属性打结了.我知道我可以通过将代码放在代码隐藏文件中来使其工作.在MVVM中有正确的方法吗?
谢谢.
The property TxtLabel is not found, I am using MVVM light. I have tyied using dependency property. I know I can make it work by puting the code in the codebehind file. Is there a correct way to do this in MVVM.
Thanks.
推荐答案
您的
TextBoxView
的DataContext
是什么?似乎您想绑定到TextBoxView
本身的属性.因此,您可以将TextBoxView
的DataContext
设置为其自身.像这样的东西:
What''s the
DataContext
of yourTextBoxView
? It seems like you want to bind to the properties of theTextBoxView
itself. So, you can set theDataContext
of theTextBoxView
to itself. Something like:
<Grid>
<v:TextBoxView DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
TxtLabel="Label 1" />
<v:TextBoxView DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
TxtLabel="Label 2" />
</Grid>
这篇关于我是MVVM的新手,有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!