簡體   English   中英

WPF中的數據綁定

[英]Databinding in WPF

我在文本塊中進行數據綁定時遇到麻煩。

我想做的是,每當在任何類中發生異常時,我都希望在Text Block中顯示它,但由於某種原因它不會消失。

Main.xaml

<Window x:Class="TestingWPF.Main"

      <Window.Resources>
        <ObjectDataProvider x:Key="showErr" ObjectType="{x:Type   local:ErrorLog}"         MethodName="GetError"/>
            </Window.Resources>
       <Frame  Name="frame1" Width="620"/>
       <Button  Name="button1"  Click="button1_Click">
       <TextBlock Name="txtBlock6" Text="{Binding Source={StaticResource showErr}}"/>
    </Window>

Main.xaml.cs

    namespace TestingWPF
    {
       public partial class Main : Window
       {
          private void button1_Click(object sender, RoutedEventArgs e)
          {
             frame1.Source =new Uri("/Page1.xaml", UriKind.Relative);     
          }
       }

      public class ErrorLog 
      {
         private string errorInfo { get; set; }

        public string GetError(string errorMessage)
        {
           return errorInfo =errorMessage;
        }
      }
   }

Page1.xaml

<Page x:Class="TestingWPF.Page1"
<Button  Name="button1"  Click="button1_Click">
<Button  Name="button2"  Click="button2_Click">
</Page>

Page1.xaml.cs

namespace TestingWPF
{
    public partial class Page1 : Page
     {
        ErrorLog errorLog = new ErrorLog ();

        private void button1_Click(object sender, RoutedEventArgs e)
        {
             someMethod1();
        }

        private void someMethod1()
        {
          try
          {
          }
          catch(Expection e)
          {
              errorLog.GetError(e.toString());// This is not dispalying 
          }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
             someMethod2();
        }

        private void someMethod2()
        {
            Class2 class2 = new Class2();
            class2.foo();  
        }
     }
}

Class2.cs

namespace TestingWPF
{
    class Class2
    {
        ErrorLog errorLog = new ErrorLog ();

        public void foo()
       {
         try
         {
          }
          catch(Expection e)
          {
              errorLog.GetError(e.toString());// This is not dispalying 
          }

       }
    }
}

您實際上在哪里設置錯誤,我只看到GetError方法,該方法僅返回傳遞給它的相同消息? 我要么添加一個無參數的GetError方法,要么綁定到您正在創建的對象的實際屬性,即創建一個可公開訪問的屬性

Error {get;set;}

在您的ErrorLog類中,然后在您的SetError方法中進行設置,即

 public string SetError(string errorMessage)
 {
    Error = errorMessage;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM