将一个字符串从MainWindow传输到UserControl中的RichTextBox

时间:2014-07-15 14:59:59

标签: c# wpf user-controls serial-port richtextbox

我是WPF的新手,我有一个名为通信的UserControl,负责将\ disconnect连接到SerialPort类。

此外,还有一个LOG是RichTextBox,我的目的是读取和写入在SerialPort缓冲区上运行的字符串,并将其显示在该日志上。

应用程序看起来像这样:

enter image description here

通讯XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0"
                Orientation="Horizontal"
                HorizontalAlignment="Center"
                Margin="0,0,0,10">
        <TextBlock Text="Choose COM:"
                   VerticalAlignment="Center"
                   />
        <ComboBox Name="ComboBoxPorts"
                  Height="25"
                  Width="75"
                  VerticalContentAlignment="Center"
                  SelectionChanged="ComboBoxPorts_SelectionChanged" />
        <Button Name="Button_open_port"
                Content="Connect"
                Height="25"
                Click="open_port_Click"/>
    </StackPanel>
    <Border BorderThickness="1" BorderBrush="Black" Grid.Row="1">
        <ScrollViewer Name="ScrollViewer_LogView"
                      VerticalScrollBarVisibility="Auto"
                      Height="220">
            <RichTextBox Name="RichTextBox_logView"
                         Height="220"
                         VerticalScrollBarVisibility="Visible" />
        </ScrollViewer>
    </Border>
</Grid>

同样在该UserControl的代码中,我有一个名为&#34; Print to log&#34;在LOG上工作并打印出我给她的字符串。

通讯CS代码:

public partial class Communication : UserControl
{
    public SerialPort mySerialPort = new SerialPort();
    public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);
    public event DataReceivedEventHandler DataReceivedEvent;

    public Communication()
    {
        InitializeComponent();
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
    }

    private void open_port_Click(object sender, RoutedEventArgs e)
    {
            // If Close
            if (mySerialPort.IsOpen == false)
            {
                mySerialPort.PortName = ComboBoxPorts.SelectedItem.ToString();
                mySerialPort.Open();
                Button_open_port.Background = new SolidColorBrush(Colors.Tomato);
                Button_open_port.Content = "Disconnect";
            }
            // If Open
            else
            {
                mySerialPort.Close();
                Button_open_port.Background = new SolidColorBrush(Colors.LightGreen);
                Button_open_port.Content = "Connect";
            }
    }

    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    { 
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        // Print it on the Log
        Print_To_Log(indata, System.Windows.Media.Brushes.Red, 0);
    }

    /// <param name="data">string of the data</param>
    /// <param name="color">object "Brushes.xxxxx"  -> (xxxxx=name of the color)</param>
    /// <param name="direction">1 for TX (sending data), 0 or anything else for RX(receiveing data)</param>
    public void Print_To_Log(string data, SolidColorBrush color, int direction = 0)
    {
        // Print it on the Log
        RichTextBox_logView.Dispatcher.BeginInvoke((Action)delegate()
        {
            TextRange rangeOfTextInput = new TextRange(RichTextBox_logView.Document.ContentEnd, RichTextBox_logView.Document.ContentEnd);
            if (direction == 1)
                rangeOfTextInput.Text = ">>  ";
            else
                rangeOfTextInput.Text = "<<  ";
            rangeOfTextInput.ApplyPropertyValue(TextElement.ForegroundProperty, color);
            RichTextBox_logView.AppendText(data + "\r");
            RichTextBox_logView.ScrollToEnd();
        });
    }

我有一个包含TextBox和Button的 MainWindow 。此外,MainWindow在XAML中包含UserControl 通信

我希望能够在该TextBox上编写一个字符串,然后在单击按钮&#34; Send&#34;后,将字符串传输到SerialPort(显示在UserControl中),它将出现在LOG上。

此外,当我在SerialPort上收到某些内容时,它也应该出现在该LOG上。

我是怎么做到的?请帮助。

MainWindow XAML:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto" />
        <RowDefinition Height="auto" />
    </Grid.RowDefinitions>
    <MyProject:Communication Grid.Row="0"
                             Margin="0,10"
                             Width="450"
                             Height="250"/>
    <WrapPanel Grid.Row="1">
        <TextBox Name="TextBox_input"
                 Width="200"
                 HorizontalAlignment="Left"
                 Margin="50,0,20,0"/>
        <Button Name="Button_send"
                Width="80"
                Content="_Send"
                Click="Button_send_Click"/>
    </WrapPanel>
</Grid>

MainWindow代码:

    public MainWindow()
    {
        InitializeComponent();
    }



    private void Button_send_Click(object sender, RoutedEventArgs e)
    {

    }

1 个答案:

答案 0 :(得分:1)

你能做的就是你可以将Name属性赋予你在mainwindow.xaml中添加的特定用户控件,然后可以获得思考

- &GT;将名称属性分配给userControl

将x:Name =“ucCommunication”添加到MyProject:Communication对象。

- &GT;现在对UserControl进行必要的更改

(制作一个助手功能)

public void GetStringDataFromControl(string content)
{
  ///write here your required function to execute when u get send button clicked and had textbox text in hand
}

- &GT;现在通过调用像这样的公共成员函数将RichTextbox Text传递给UserControl

private void Button_send_Click(object sender, RoutedEventArgs e)
{
      //here call usecontrol helper function 
     ucCommunication.GetStringDataFromControl("write the string you want to pass.Here in your case get richtextbox text and convert it to string and pass");
}

如有任何疑问或疑虑,请告诉我。如果确实有帮助那么请将其标记为答案。