簡體   English   中英

XAML代碼中的C#變量

[英]C# variable in XAML code

我在XAML表單后面有部分類代碼。 這是背后的代碼:

partial class GalleryDictionary
{
    private void GalleryItemLabelPropertyChanged(object sender, RoutedEventArgs e)
    {
        var mainWindow = Application.Current.MainWindow as MainWindow;
        if (mainWindow == null)
            return; 

        var tb = sender as TextBox;
        if (tb == null)
            return;

        var sip = tb.DataContext as StereoImagePair;
        if (sip == null)
            return;

        sip.Label = tb.Text;

        mainWindow.Db.SubmitChanges();
    }
}

那就是命名空間聲明之后的整個DOC.XAML.CS文件。

在我的XAML文件中,我需要從該XAML.CS文件訪問一個我想調用DriveOnRight的變量。 這是我一直在爭取的路線:

        <ToggleButton Grid.Row="1" Grid.Column="2" Width="26" Height="26" IsChecked="True" Click="GalleryItemLabelPropertyChanged" CommandParameter="2" Name="PS" Content="{Binding DriveOnRight}"></ToggleButton>

XAML文件讀取的位置。...Content =“ {Binding DriveOnRight}”是我需要從CS文件訪問變量並將其顯示的地方。

我怎么做?

任何幫助肯定將不勝感激。

看到這是在您的代碼后面,為了與您的方法保持一致,您可以將依賴項屬性用作值。

public string DriveOnRight
{
    get { return (string)GetValue(DriveOnRightProperty); }
    set { SetValue(DriveOnRightProperty, value); }
}
public static readonly DependencyProperty DriveOnRightProperty =
    DependencyProperty.Register("DriveOnRight", typeof(string), typeof(GalleryDictionary));

盡管我會建議使用ViewModel來使Krish的設計更好。

這是一種方法:

public class GalleryDictionaryViewmodel: INotifyPropertyChanged
{
     private string _DriveOnRight;
     public string DriveOnRight
     {
         get{ return _DriveOnRight;}
         set{ _DriveOnRight = value;}
     }
}

在您的CodeBehind文件(DOC.XAML.CS)中:

partial class GalleryDictionary
{
      public GalleryDictionaryViewModel GDViewModel;
      public GalleryDictionary()
      {
          GDViewMOdel = new GDViewModel();
          GDViewModel.DriveOnRight = "";
          this.DataContext = GDViewModel;
      }
}

在您的Xaml文件中:

 <ToggleButton Grid.Row="1" Grid.Column="2" Width="26" Height="26" IsChecked="True" Click="GalleryItemLabelPropertyChanged" CommandParameter="2" Name="PS" Content="{Binding DriveOnRight}"></ToggleButton>

希望這會幫助你。

您可以在后面的代碼中分配一個值,該值與按鈕或切換按鈕或任何使用它的對象的LOADED功能相關聯。

在您要設置值的功能之上的級別中,編寫如下代碼。

    public static string DriveOnRight = "True";  
    //"True" could be a condition or function or whatever.

然后,在后面的代碼中可能看起來像這樣:

    private void DS_Loaded(object sender, RoutedEventArgs e)
    {
        ToggleButton tg = sender as ToggleButton;
        if (//WhateverYourPathToTheVariable//.DriveOnRight == "True")
        {
            tg.Content = "DS"; 
        }
        else
        {
            tg.Content = "PS";
        }

    }

然后...在XAML代碼中,您有以下內容:

        <ToggleButton Loaded="DS_Loaded" Grid.Row="1" Grid.Column="0" Width="26" Height="26" Name="DS" Content="DS"></ToggleButton> 

暫無
暫無

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

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