1

假设我有这两个用户控件。当单击按钮时,如何将在 TextBoxControlOne中输入的数据传递到 TextBox ?ControlTwoControlOne

<UserControl x:Class="Project.ControlOne"
             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"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <StackPanel Orientation="Horizontal">
            <TextBox x:Name="MyTextBox" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" />
            <Button HorizontalAlignment="Center" VerticalAlignment="Center" Content="Send" Click="Button_Click" />
        </StackPanel>
    </Grid>
</UserControl>

...
namespace Project
{
    public partial class ControlOne : UserControl
    {

        public ControlOne()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

<UserControl x:Class="Project.ControlTwo"
             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"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <StackPanel Orientation="Horizontal">
            <TextBox x:Name="MyTextBox" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" />
        </StackPanel>
    </Grid>
</UserControl>
4

1 回答 1

1

Your two user controls should have no knowledge of each other (unless one contains the other). That's why you can't "pass data" between them. The idea behind a user control is that you can drop it anywhere as many times as needed. If ControlOne knew about ControlTwo, what would happen if you used them separately? Or had three ControlTwos in the same place?

The layer which contains both of them should be the one to read a value from one and set it to the other. If you want it to happen on the button press, you should look into event handling so the parent can know when the control's button is pressed.

于 2013-04-03T21:15:27.453 回答