0

.xamlにテキストボックスとボタンがあります。ボタンをクリックすると、ファイルダイアログを開くことができ、ファイルを選択することもできます。

MainWindow.Xaml:

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

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

私のViewModelクラス:

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

あなたはインターフェースを介してこれを行うことができます:

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();
        }
    }

次に、ViewModelのコンストラクターまたはプロパティを介してこれをインスタンス化できます。

  public ViewModel(IFileReader FileReader) // constructor
        { }

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

それが役に立てば幸い

于 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 に答える