0

我的 .xaml 中有一个文本框和一个按钮。当我单击按钮时,我能够打开一个文件对话框并能够选择文件。

主窗口.Xaml:

<TextBox Height="93" IsReadOnly="True" Text="{Binding Path=ReadMessage, Mode=TwoWay}" Name="MessageRead" />

<Button Content="Load" Name="I2CLoadBtn" Command={Binding Path = LoadContentCommand />

我的视图模型类:

public static RelayCommand LoadContentCommand { get; set; }

    private string _ReadMessage;
    public string ReadMessage
    {
        get { return __ReadMessage; }
        set
        {
            __ReadMessage= value;
            NotifyPropertyChanged("ReadMessage");
        }
    }

    private void RegisterCommands()
    {
        LoadContentCommand = new RelayCommand(param => this.ExecuteOpenFileDialog());
    }

    private void ExecuteOpenFileDialog()
    {
        var dialog = new OpenFileDialog { InitialDirectory = _defaultPath };
        dialog.ShowDialog();
        dialog.DefaultExt = ".bin";
        dialog.Filter = "Bin Files (*.bin)|*.bin";           
    }

我基本上想要的是,一旦选择了文件,文件的内容必须保存到文本框中。例如,如果我要加载一个 .txt 文件,则在加载内容时必须将其放在文本框中。

请帮忙!!!

4

3 回答 3

0

You can do this via an interface :

public interface IFileReader
    {
        string Read(string filePath);
    }
    public class FileReader : IFileReader
    {
        public string Read(string filePath)
        {
           byte[] fileBytes = File.ReadAllBytes(filePath);
            StringBuilder sb = new StringBuilder();
            foreach(byte b in fileBytes)
            {
                sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
            }
            return sb.ToString();
        }
    }

Then you can instantiate this via you ViewModel's constructor or property :

  public ViewModel(IFileReader FileReader) // constructor
        { }

public IFileReader FileReader { get; set; } // property

Hope it helps

于 2012-09-27T07:23:24.257 回答
0

这是您获得所选路径的方式:

string path = "";
if (dialog .ShowDialog() == true)
{
    path = dialog.FileName;
}

using (StreamReader sr = new StreamReader(path)) 
{
     ReadMessage = sr.ReadToEnd()
}
于 2012-09-27T08:19:32.083 回答
0

我喜欢使用File.ReadAllText读取文本文件的语法。

string readText = File.ReadAllText(path);
于 2012-09-28T01:15:01.130 回答