我有一个Silverlight项目,我正在转换为MVVM。这是我第一次使用这种模式而且我正在努力解决问题。
所以基本上我在后面的XAML代码中有这个:
OpenFileDialog ofd = new OpenFileDialog();
if ((bool)ofd.ShowDialog())
{
_fileName = ofd.File.Name;
FileStream fs = ofd.File.OpenRead();
fileSize = (double)fs.Length;
txtFileName.Text = fileName;
index = 0;
sendData = 0;
byte[] file = new byte[fs.Length];
fs.Read(file, 0, file.Length);
//convertToChunks(file);
prgUpload.Maximum = fileChunks.Count;
prgUpload.Value = 0;
//uploadChunks(index);
}
我无法弄清楚如何将它连接起来以便能够在模型中使用它?我假设viewmodel发挥作用,但没有任何工作。
有什么想法吗?
以下是正在进行的工作XAML:
<Grid x:Name="LayoutRoot" Width="475" Height="340">
<Canvas Margin="8,8,0,0" Background="White" Height="320" VerticalAlignment="Top" HorizontalAlignment="Left" Width="475">
<Button Width="75" Canvas.Left="380" Canvas.Top="43" Content="Browse" x:Name="btnBrowse" />
<TextBox Canvas.Left="25" IsReadOnly="True" Canvas.Top="43" TextWrapping="Wrap" Width="350" Text="{Binding Path=FileUploadName}" x:Name="txtFileName" />
<ProgressBar Height="10" Width="350" Canvas.Left="25" Canvas.Top="99" x:Name="prgUpload" />
<my:Label Content="Please select a file to upload" Name="lblError" Canvas.Left="25" Canvas.Top="23" RenderTransformOrigin="0.133,-0.063" Width="220"/>
<my:Label x:Name="lblProgress" Canvas.Left="25" Canvas.Top="78" RenderTransformOrigin="0.133,-0.063" Width="220"/>
</Canvas>
</Grid>
基本上我希望在用户选择要上传的文件后触发它。
答案 0 :(得分:2)
如果您要发出命令,这将为您完成工作
<Button Width="75" Canvas.Left="380" Canvas.Top="43" Content="Browse" x:Name="btnBrowse"
Command={Binding OpenFileCommand} />
在构造函数后面的代码中,例如
partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
this.DataContext=new MainViewModel();
}
}
并在您的ViewModel中
public ICommand OpenFileCommand { get; set; }
public MainViewModel()
{
OpenFileCommand = new RelayCommand(OpenDialog) { IsEnabled = true };
}
private void OpenDialog()
{
OpenFileDialog ofd = new OpenFileDialog();
if ((bool)ofd.ShowDialog())
{
_fileName = ofd.File.Name;
FileStream fs = ofd.File.OpenRead();
fileSize = (double)fs.Length;
//txtFileName.Text = fileName;// Apply Binding
index = 0;
sendData = 0;
byte[] file = new byte[fs.Length];
fs.Read(file, 0, file.Length);
//convertToChunks(file);
prgUpload.Maximum = fileChunks.Count;
prgUpload.Value = 0;
//uploadChunks(index);
}
}
和RelayCommand
public class RelayCommand:ICommand
{
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
if (value != _isEnabled)
{
_isEnabled = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
private Action _handler;
public RelayCommand(Action handler)
{
_handler = handler;
}
public bool CanExecute(object parameter)
{
return IsEnabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
}
要在文本框中获取文件名,您必须将文本框绑定到视图模型。这样它就会出现在UI上并实现INotifyPropertyChanged。另外看看这会有用Silverlight MVVM