且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UserControl和Windows之间的交互

更新时间:2023-12-06 13:52:34

有几种方法来处理这种沟通。这里只是一些方法...还有更多的东西:



1)定义一个命令...当您点击它时,您的按钮将会提升。



然后在您的窗口中,您将处理该命令,并将TextBox更改为某些字符串。



您可以如果要提供一些数据/上下文,请使用CommandParameter。



2)定义一个冒泡树的RoutedEvent(冒泡的),然后Window可以处理它。事件将由您的Button在UserControl中提出,并将包含您想在窗口中设置的文本。



3)如果您的某事是一种状态指示符,那么您可以在您的UserControl(或另一个选项具有包含状态数据的ViewModel)中提供状态属性。然后,您的TextBox可以绑定到您的UserControl(或ViewModel)上的该属性,以获取状态(作为一个值,然后被转换为具有转换器的可显示消息,或作为直接字符串)。


I've created a UserControl which contains some conrols (buttons and checkboxes).

After that I added a reference to that UserControl in my WPF Windows.

What I want to do is : when I click in a button in the UserControl this button fires an action and change something in the Windows (Textbox1.Text = "something").

My problem is that I can't access to controls inside the Windows from the UserControl.

Any help please ?

EDIT : Added code sample

<s:SurfaceWindow x:Class="Project.Temp.MainSurface"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:s="http://schemas.microsoft.com/surface/2008"
                 xmlns:local="clr-namespace:Project"              
                 Title="Project.Temp"
>
<Grid x:Name="Root" ... >
     <Grid x:Name="Child" ... >
         <local:MyUserControl x:Name="UserControlStart" ... />
     </Grid>
...
</Grid>

There are several ways to approach this "communication"...here are just some of the ways...there are plenty more:

1) Define a Command...which your button will raise when it is clicked.

Then in your Window you will handle that command, and change the TextBox to some string.

You can use a CommandParameter if you want to provide some data/context.

2) Define a RoutedEvent (bubbling one) which bubbles up the tree and a Window can then handle it. The event would be raised by your Button in the UserControl and would contain the "text" you wanted to be set in the Window.

3) If your "something" is kind of a "state" indicator...then you could provide a "state" property on your UserControl (or another option have a ViewModel which contains the state data instead). Then your TextBox could bind to that property on your UserControl (or ViewModel) to obtain the "state" (either as a value which then is "converted" into a displayable message with a converter, or as a direct string).