我是MVVM的新手,有问题 [英] I am new to MVVM and having a problem

查看:78
本文介绍了我是MVVM的新手,有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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.

推荐答案

您的TextBoxViewDataContext是什么?似乎您想绑定到TextBoxView本身的属性.因此,您可以将TextBoxViewDataContext设置为其自身.像这样的东西:

What''s the DataContext of your TextBoxView? It seems like you want to bind to the properties of the TextBoxView itself. So, you can set the DataContext of the TextBoxView 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆