2016-06-17 6 views
2

저는 C# UWP 개발에서 새로 왔으며 런타임에 TextBlock의 값을 변경하려고했지만 바인딩이 제대로 작동하지 않습니다.런타임에 텍스트 블록 바인딩이 업데이트되지 않습니다.

XAML에서 TextBlock의 text 속성을 INotifyPropertyChanged를 사용하는 ViewModel의 속성에 바인딩하고 10 초마다 값이 변경됩니다.

올바른 방법인지 모르겠지만 누군가 나를 도울 수 있습니까?

미리 감사드립니다.

and the XAML code

class MainPaigeViewModel : INotifyPropertyChanged 
{ 

    public MainPaigeViewModel() 
    { 
     Task.Run(async() => 
     { 
      Random random = new Random(); 
      while (true) 
      { 
       await Task.Delay(10000); 
       int newValue = random.Next(-40, 40); 
       _MyValue = newValue.ToString(); 
       Debug.WriteLine(MyValue); 
      } 
     }); 
    } 

    //Properties 
    private string _MyValue; 
    public string MyValue 
    { 
     get { return _MyValue; } 
     set 
     { 
      _MyValue = value; 
      RaisePropertyChanged("MyValue"); 
     } 
    } 


    //INotifyPropertyChanged 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected void RaisePropertyChanged(string name) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); 
    } 
} 

this is the ViewModel code

<Page 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="using:CountDown2" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:ViewModels="using:CountDown2.ViewModels" 
    x:Class="CountDown2.MainPage" 
    mc:Ignorable="d"> 

    <Page.DataContext> 
     <ViewModels:MainPaigeViewModel/> 
    </Page.DataContext> 

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
     <RelativePanel VerticalAlignment="Center" HorizontalAlignment="Center"> 
      <TextBlock Text="{Binding MyValue, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 
         Width="100" 
         Height="40" 
         TextAlignment="Center" 
         FontSize="20" 
      /> 
     </RelativePanel> 
    </Grid> 
</Page> 
+0

당신은 Raisepropertychange 방법에 중단 점을 넣어 확인할 수 있습니까? – riteshmeher

+0

외부 링크가 아닌 질문에 적절한 위치에서 코드를 제공하십시오. 여기 왜 [mcve]를주는 것이 중요한지보십시오. – dymanoid

+0

@riteshmeher RaisePropertyChanged가 실행되지 않고 있습니다. 무엇이 문제입니까? – CGuiVi

답변

0

. 바인딩은 응용 프로그램이 시작될 때 한 번 발생합니다. 단방향 바인딩은 WinRT, Silverlight 및 wpf의 기본값입니다. 뷰가 업데이트되지만 뷰를 업데이트해도 뷰 모델은 업데이트되지 않습니다. 양방향 바인딩은보기와보기 모델을 모두 업데이트합니다.

예에서 <TextBlock>의 경우 One Way 바인딩을 사용하는 것이 좋습니다.

<TextBox> 사용자 입력을 위해 Two Way 바인딩을 사용하는 것이 좋습니다.

바인딩이 실패하는 몇 가지 작은 버그가 발견되어 뷰 모델을 변경했습니다. 공개 속성이 아닌 개인 속성이 사용되었습니다. 코드가 스레드의 값을 업데이트 한 다음 스레드에서 객체를 마샬링하려는 경우 디스패처가 추가되었습니다. 또한 모든 뷰 모델에 공통 기본 클래스가 추가되었습니다. 이것은 속성 바인딩을 좀 더 쉽게 만들어 주며, 속성 이름을 리팩토링 할 때 바인딩 문제를 방지합니다. 바인딩 :

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync

public class MainPaigeViewModel: ViewModelBase 

{ 


    public MainPaigeViewModel() 
    { 
     Task.Run(async() => 
     { 
      Random random = new Random(); 
      while (true) 
      { 
       await Task.Delay(1000); 
       int newValue = random.Next(-40, 40); 
       try 
       { 
        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
        () => { 
         MyValue = newValue.ToString(); 
        }); 

       } 
       catch (Exception ex) 
       { 
        string s = ex.ToString(); 
       } 
       Debug.WriteLine(MyValue); 
      } 
     }); 
    } 

    //Properties 
    private string _MyValue; 
    public string MyValue 
    { 
     get { return _MyValue; } 
     set 
     { 
      _MyValue = value; 
      OnPropertyChanged(); 
     } 
    } 


} 



public abstract class ViewModelBase : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged = delegate { }; 


    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 

     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

은 또한 X를 사용하여 뷰를 변경. 나는 런타임시보다 컴파일 타임에 바인딩 문제를 보여주기 때문에 x : old data binding에 대한 바인딩을 좋아한다. 이것은 성능 향상 외에도 있습니다. x의 코드 뒤에

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
     <RelativePanel VerticalAlignment="Center" HorizontalAlignment="Center"> 
      <TextBlock Text="{x:Bind viewModel.MyValue, Mode=OneWay}" 
         Width="100" 
         Height="40" 
         TextAlignment="Center" 
         FontSize="20" 
      /> 
     </RelativePanel> 
    </Grid> 

페이지 :이 발사되면 바인드는

public sealed partial class MainPage : Page 
{ 
    public MainPaigeViewModel viewModel; 

    public MainPage() 
    { 
     this.InitializeComponent(); 

     viewModel = new MainPaigeViewModel(); 
    } 


} 
0

시도 : 실버 라이트와 WPF 바인딩 기본은 성능상의 이유로 한 시간을 달리 UWP에서 Text="{Binding MyValue, Mode=TwoWay}"

+0

답장을 보내 주셔서 감사합니다. @D. Nehl하지만 여전히 같은 문제 – CGuiVi

관련 문제