【发布时间】:2018-02-11 17:55:42
【问题描述】:
RootObject.cs
public class RootObject
{
private const string api = "";
private const string mode = "json";
private const string url = "http://api.openweathermap.org/data/2.5/weather?q=";
public Coord coord { get; set; }
public void Get(string city)
{
JObject jsonData = JObject.Parse(new WebClient().DownloadString(url + city + "&appid=" + api + "&mode=" + mode));
coord = new Coord(jsonData.SelectToken("coord"));
}
}
Coord.cs
public class Coord
{
private double lon;
public double Lon
{
get { return lon; }
set { lon = value;}
}
private double lat;
public double Lat
{
get { return lat; }
set { lat = value;}
}
public Coord(JToken coorddata)
{
this.Lon = Convert.ToDouble(coorddata.SelectToken("lon"));
this.Lat = Convert.ToDouble(coorddata.SelectToken("lat"));
}
}
ViewModel.cs
public class ViewModel
{
public ICommand MyCommand { get; set; }
public ViewModel()
{
MyCommand = new RelayCommand(ExecuteMyMethod, CanExecuteMyMethod);
}
private string city;
public string City
{
get { return city; }
set { city = value; }
}
private bool CanExecuteMyMethod(object parameter)
{
if (string.IsNullOrEmpty(City))
{
return false;
}
else
{
if (City != "")
{
return true;
}
else
{
return false;
}
}
}
private void ExecuteMyMethod(object parameter)
{
RootObject a = new RootObject();
a.Get(City);
}
}
MainWindow.xaml
<Window.Resources>
<vm:ViewModel x:Key="viewModel"></vm:ViewModel>
</Window.Resources>
<Grid >
<StackPanel>
<StackPanel DataContext="{Binding Source={StaticResource viewModel}}">
<TextBox Width="100" Height="30" Text="{Binding City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<Button Width="100" Height="30" Command="{Binding MyCommand }">pussh</Button>
</StackPanel>
<StackPanel DataContext="{Binding Source={???}}">
<Label></Label>
<TextBox Width="100" Height="100" Text="{Binding Path=Lon}"></TextBox>
<TextBox Width="100" Height="50" Text="{Binding Path=Lat}"></TextBox>
</StackPanel>
</StackPanel>
</Grid>
我是 MVVM 方面的新手。
我尝试将属性Lat 和Lon 绑定到XAML 中的文本框(单击按钮后将显示Lat 和Lon),已经使用DataContext 和ObjectDataProvider 进行了测试,但它不起作用.我想我忘记了一些东西,但不知道它应该是什么。
【问题讨论】:
标签: c# wpf xaml mvvm data-binding