내 UWP 앱에서 API 호출에서 반환 된 데이터를 기반으로 UI를 업데이트하고 있습니다. MyPage
API 호출에서 다시 조정 된 데이터를 표시하는 페이지입니다.
public sealed partial class MyPage : Page
{
private MyViewModel _viewModel;
private MyApiResponse _result;
private string _documentId;
public DocumentDetailsPage()
{
this.InitializeComponent();
_viewModel = new MyViewModel();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_documentId = (string)e.Parameter;
await GetDocumentDetails();
}
private async Task GetDocumentDetails()
{
//THIS WORKS, BUT USING await INSTESD OF .Result DOESN'T UPDATE THE VIEW
_result = new MyApiCall(_documentId).GetResponseAsync().Result;
PrepareViewModel();
}
private void PrepareViewModel()
{
viewModel.Type = _result.response.type;
viewModel.VolumeNumber = _result.response.volumeNumber;
}
}
다음은 API에 Http-POST 요청을하는 클래스입니다.
public class MyApiCAll
{
...
...
public async Task<MyApiResponse> GetResponseAsync()
{
MyApiResponse responseObject;
using(HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("ABC", ABC);
var response = await _client.PostAsync("someURL", null).ConfigureAwait(false);
var responseJson = await response.Content.ReadAsStringAsync();
responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<MyApiResponse>(responseJson);
}
return responseObject;
}
}
그리고 여기에 내 견해가 있습니다.
<StackPanel Style="{StaticResource ContainerStackPanel}"
Visibility="{x:Bind viewModel.Type, Converter={StaticResource ConverterNameHere}, Mode=OneWay}">
<TextBlock Text="ABC"/>
<TextBlock Text="{x:Bind viewModel.Type, Mode=OneWay}"/>
</StackPanel>
<StackPanel Style="{StaticResource ContainerStackPanel}"
Visibility="{x:Bind viewModel.volumeNumber, Converter={StaticResource ConverterNameHere}, Mode=OneWay}">
<TextBlock Text="ABC"/>
<TextBlock Text="{x:Bind viewModel.volumeNumber, Mode=OneWay}"/>
</StackPanel>
이것은 UI를 차단한다는 점을 제외하고는 완벽하게 작동하므로 Result
메서드 호출에서를 제거하고 다음과 같이 await를 추가 할 때 :
_result = await new DocumentDetailsApiCall(_documentId).GetResponseAsync();
그런 다음 내 UI에 바운드 값이 표시되지 않고 비어 있습니다. viewModel 속성이 업데이트되었는지 확인할 수 있습니다.
INotifyPropertyChanged
내 ViewModel 속성을 구현하지 않습니다 (구현 을 시도했지만 변경하지 않았습니다)
업데이트 제안 된대로, INPC
내 viewModel에 추가 했고 여기에 내 ViewModel 클래스를 추가했습니다.
class MyViewModel : INotifyPropertyChanged
{
private string _type;
public string Type
{
get { return _type; }
set
{
_type = value;
this.OnPropertyChanged();
}
}
private string _volumeNumber;
public string VolumeNumber
{
get { return _volumeNumber; }
set
{
_volumeNumber = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
문제가 남아 있습니다. await
연산자를 사용할 수 없습니다. .Result
여전히 작동합니다.
호출이 Bindings.Update()
문제를 해결 했으므로 바인딩식이 정확해야하지만 속성 변경 알림이 실패합니다.
여기서 실제로 무엇이 잘못되었는지 추측하지 않고 언제를 사용해야 Bindings.Update()
하고 언제 INPC
+ OneWay
바인딩을 사용해야하는지 설명합니다 .
Bindings.Update()
만 사용할 수 있습니다 x:Bind
귀하의 UI는 거의 새 데이터로 업데이트 할 필요가없는 경우 바인딩 전통, 당신은 구현할 필요가 없습니다 달리, INPC
사실,이 일을 실제로 훨씬 저렴하고 더 성능이 좋은이다, 당신의 재산과 OneTime
(전화와 바인딩을 Bindings.Update()
구현하는 것보다) INPC
와 OneWay
바인딩.
따라서 다음은 x:Bind
-
<TextBlock Text="{x:Bind MyText}" Style="{StaticResource SubheaderTextBlockStyle}" />
public string MyText { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
MyText = "new text!!";
Bindings.Update();
}
버튼을 클릭하면 새 텍스트TextBlock
로 채워집니다 !! . 내가 기본 사용 여기에 참고 OneTime
바인딩 (즉 {x:Bind MyText}
) 및 MyText
단지 AA 정상 CLR 속성입니다.
이것은 Bindings.Update()
마지막에 호출했기 때문에 작동하며 OneTime
바인딩이 다시 초기화됩니다.
그러나 앞서 말했듯이 UI 업데이트가 거의 필요 하지 않은 경우에만 위의 접근 방식을 사용하는 것이 좋습니다. 대부분의 경우 그렇지 않으므로 전혀 사용할 필요없이 바인딩을 구현 INPC
하고 작성 합니다.OneWay
Bindings.Update()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다