wpf属性绑定到MVVM中的文本块?

时间:2014-02-01 21:04:27

标签: c# wpf data-binding

我有一个文本块,我正在尝试将数据绑定到我的viewModel中的属性,我无法让它更新,这里是代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        FurnaceDataViewModel viewModel = new FurnaceDataViewModel();
        InitializeComponent();
    }
}

class FurnaceDataViewModel: ObservableObject
{
    public FurnaceDataModel dataModel = new FurnaceDataModel();
    public SerialPort serialPort = new SerialPort();

    public FurnaceDataViewModel()
    {            
        serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
        try
        {
            if (serialPort.IsOpen != true)
                serialPort.Close();
            serialPort.Open();
            serialPort.DataReceived += new SerialDataReceivedEventHandler(serialReceivedData); 
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    public void serialReceivedData(object sender, SerialDataReceivedEventArgs e)
    {
        dataModel.IncomingMessage = serialPort.ReadExisting();            
    }
}

class FurnaceDataModel: ObservableObject
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string incomingMessage;

    public string IncomingMessage
    {
        get { return incomingMessage; }
        set
        {
            incomingMessage = value;
            OnPropertyChanged("IncomingMessage");
        }
    }
}

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:FurnaceData" x:Class="FurnaceData.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <TextBlock x:Name="tbkMain" HorizontalAlignment="Left" Height="292" Margin="10,10,0,0" TextWrapping="Wrap" Text="{Binding dataModel.IncomingMessage}" VerticalAlignment="Top" Width="489"/>
</Grid>

如何在数据绑定时将文本块文本换行?喜欢+ =有点儿的东西?

1 个答案:

答案 0 :(得分:1)

我认为您需要设置datacontext或设置objectDataProvider。

在构造函数中,尝试添加行

DataContext = viewModel;

将您的字段更改为属性

public class FurnaceDataViewModel
{
    public FurnaceDataModel dataModel { get; set; }

你应该看到你的文字包装,但是你很难看到你的文本块代码设置为绝对大小...试试看它的包装

 <TextBlock x:Name="tbkMain" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  Margin="10,10,0,0" TextWrapping="Wrap" 
               Text="{Binding Path=dataModel.IncomingMessage}" />