简体   繁体   English

绑定到ViewModel和可重复使用的UserControl背后的Code

[英]Binding to ViewModel and CodeBehind a reusable UserControl

I have a usercontrolX that i created to use it more than one time in a PageX view. 我创建了一个usercontrolX ,以便在PageX视图中多次使用它。 it contains a button and a textbox , and i want to bind the textbox to a property in PageXModelView and the button should do something in my usercontrolXModelView . 它包含一个按钮和一个文本框,我想将文本框绑定到PageXModelView中的属性,并且该按钮应在usercontrolXModelView中执行某些操作。

The problem is when i add the usercontrolX to the view i can bind it to the PageX property only if i bind the textboxt to a usercontrolX behind code and not in the usercontrolXModelView and for the button it works only if I bind it to a property in usercontrolXModelView , So is there a solution to bind the usercontrolX to the usercontrolXModelView and the usercontrolX behind code 问题是,当我将usercontrolX添加到视图中时,仅当我将文本框绑定到代码背后usercontrolX而不是在usercontrolXModelView中时 ,我才能将其绑定到PageX属性,并且对于按钮,仅当我将其绑定到其中的属性时,该按钮才起作用usercontrolXModelView ,是否有解决方案将usercontrolX绑定到usercontrolXModelView代码后面usercontrolX

  • Here is project : 这是项目:

Views : UserControlX , Page , MainWindow 视图:UserControlX,Page,MainWindow

ModelViews : UserControlXMV, PageMV , MainWindowMV ModelViews:UserControlXMV,PageMV,MainWindowMV

< UserControl x:Class="APPia.Views.Usercontrolx" mc:Ignorable="d"  Name="Usercontrolx">
    < Button Name="B1" Content="Button" Command="{Binding UpdateCommandx, Mode=OneWay}"/>
    < Label Name="L21" Content="{Binding Path=propX,ElementName=Usercontrolx}"/>
</UserControl>


<UserControl x:Name="PageX"">
<Grid>
<TextBox Text="{Binding persowxn.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<UserControlX x:Name="Contx1" propX="{Binding persowxn.Name}" />
<UserControlX x:Name="Contx2" propX="{Binding persowxn.Surname}" />
</Grid>
</UserControl>

In your user control's code-behind, add a dependency property. 在用户控件的代码后面,添加一个依赖项属性。 Then bind the user control's label's content to that dependency property. 然后将用户控件的标签内容绑定到该依赖项属性。 And then bind the user control's dependency property to your page's view model's property. 然后将用户控件的依赖项属性绑定到页面的视图模型的属性。

Same for the button inside the user control... 用户控件内的按钮相同...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM