我有适用于Model View ViewModel的应用程序。 在我的模型中,我有一个基于我的客户端类的列表。如何使用RelayCommand
public class Client
{
public string Name { get; set; }
public string Ip { get; set; }
public string Mac { get; set; }
}
在我的ClientRepository中,我用我的Client类从XML文件中创建一个List。
public ClientRepository()
{
var xml = "Clients.xml";
if (File.Exists(xml))
{
_clients = new List<Client>();
XDocument document = XDocument.Load(xml);
foreach (XElement client in document.Root.Nodes())
{
string Name = client.Attribute("Name").Value;
string Ip = client.Element("IP").Value;
string Mac = client.Element("MAC").Value;
_clients.Add(new Client() { Mac = Mac, Name = Name, Ip = Ip });
}
}
}
在我的UI/UX我有3个文本框1 MAC,1个IP和1名我也有一个按钮,这就是有一个结合AddClientCommand。
<Label Grid.Row="0" Grid.Column="0" Content="Host Name:"/>
<TextBox Grid.Row="0" Grid.Column="1" x:Name="tbHostName" Height="20" Text="{Binding Path=newClient.Name, UpdateSourceTrigger=PropertyChanged}"/>
<Label Grid.Row="1" Grid.Column="0" Content="IP Address:"/>
<TextBox Grid.Row="1" Grid.Column="1" x:Name="tbIP" Height="20" Text="{Binding Path=newClient.Ip, UpdateSourceTrigger=PropertyChanged}"/>
<Label Grid.Row="2" Grid.Column="0" Content="MAC Address"/>
<TextBox Grid.Row="2" Grid.Column="1" x:Name="tbMAC" Height="20" Text="{Binding Path=newClient.Mac, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Row="3" Grid.Column="0" Content="Remove" x:Name="bRemove" Margin="3 0 3 0" Click="bRemove_Click"/>
<Button Grid.Row="3" Grid.Column="1" Content="Add" x:Name="bAdd" Margin="3 0 3 0" Click="bAdd_Click" Command="{Binding AddClientCommand}"/>
来到我的观点:我想知道的是什么,是落实AddClientCommand的最佳方式?
什么我现在有,我知道这是行不通的:
public ClientViewModel()
{
_repository = new ClientRepository();
_clients = _repository.GetClients();
WireCommands();
}
private void WireCommands()
{
AddClientCommand = new RelayCommand(AddClient);
}
public Client newClient
{
get
{
return _newClient;
}
set
{
_newClient = value;
OnPropertyChanged("newClient");
AddClientCommand.isEnabled = true;
}
}
public void AddClient()
{
_repository.AddClient(newClient);
}
RelayCommand类:
public class RelayCommand : ICommand
{
private readonly Action _handler;
private bool _isEnabled;
public RelayCommand(Action handler)
{
_handler = handler;
}
public bool isEnabled
{
get { return true; }
set
{
if (value != isEnabled)
{
_isEnabled = value;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
public bool CanExecute(object parameter)
{
return isEnabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_handler();
}
}
这是什么意思“它不工作”?你有调试吗?什么不工作? – Jviaches
我新来MVVM和AddClientCommand不起作用 –
当你点击按钮ADD时,是得到AddClient()方法吗? – Jviaches