所有字段在数据框上都标记为twoway,但很明显我有问题。我拥有的页面显示了一个视图,可以在视图的一侧添加新设备,以及另一侧的设备列表。.我要做的是从ListView选择项目时,它将更新值在文本框中查看和编辑目的。
当我创建新设备时,当前的保存选项(下面的代码未显示(当前有效,并将刷新列表。但是,现在完成后,我将返回一个框架。我想做的就是单击"保存"时刷新ListView。
XAML页面的值
<TextBox PlaceholderText="Host Name" Text="{x:Bind ViewModel.HostName, Mode=TwoWay}" Name="hostNameTB" AcceptsReturn="True" />
<TextBox PlaceholderText="Drive Model" Text="{x:Bind ViewModel.DriveModel, Mode=TwoWay}" Name="driveModelTB" />
<TextBox PlaceholderText="Drive SN" Text="{x:Bind ViewModel.DriveSN, Mode=TwoWay}" Name="driveSNTB" AcceptsReturn="True" InputScope="Digits"/>
来自ViewModel的代码
private Device _ActiveDevice;
private int _HostName;
//All Variables Created for DataBinding to XAML page
//public int HostName { get { return _HostName; } set { _ActiveDevice.HostName = value; } }
public int HostName { get; set; }
public string DriveModel { get; set; }
public string DriveSN { get; set; }
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
{
Value = (suspensionState.ContainsKey(nameof(Value))) ? suspensionState[nameof(Value)]?.ToString() : parameter?.ToString();
await Task.CompletedTask;
var uri = new Uri("http://localhost:2463/api/Devices");
HttpClient client = new HttpClient();
try
{
var JsonResponse = await client.GetStringAsync(uri);
var devicesResult = JsonConvert.DeserializeObject<List<Device>>(JsonResponse);
Devices = devicesResult;
_ActiveDevice = JsonConvert.DeserializeObject<List<Device>>(JsonResponse)[0];
}
catch
{
MessageDialog dialog = new MessageDialog("Unable to Access WebService at this Time!");
await dialog.ShowAsync();
}
//client.Dispose();
}
public void deviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var device = ((sender as ListView).SelectedItem as Device);
_ActiveDevice = device;
HostName = device.HostName;
DriveModel = device.DriveModel;
DriveSN = device.DriveSN;
}
您必须从inotifyPropertychanged继承视图模型,以让绑定知道该值的更新。
public class MainViewModel: INotifyPropertyChanged
{
public int HostName { get => hostName; set { hostName = value; OnPropertyChanged("HostName"); } }
private int hostName;
...
void OnPropertyChanged(String prop)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
public event PropertyChangedEventHandler PropertyChanged;
}
将您的绑定(以及其他所有绑定(更新:
<TextBox PlaceholderText="Host Name" Text="{Binding ViewModel.HostName, UpdateSourceTrigger=PropertyChanged}" Name="hostNameTB" AcceptsReturn="True" />
我已经离开了..我的修复程序更多是鲁福爵士提出的。然后确保所选的设备已更新每个属性。
private int _HostName;
public int HostName { get { return _HostName; } set { Set(ref _HostName, value); } }
public void deviceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var device = ((sender as ListView).SelectedItem as Device);
//_ActiveDevice = device;
HostName = device.HostName;
DriveModel = device.DriveModel;
DriveSN = device.DriveSN;