如何从自己的XAML属性中设置Xaml代码。例如“ this”

时间:2019-06-13 14:38:19

标签: xaml xamarin

我有Xamarin表单MasterDetailPage Xaml代码.xaml.cs文件,我在其中创建了字符串属性。

我想从前端Xaml设置该属性。 我知道这似乎是个新手问题,但是对于大声哭泣,我什么也无法工作。

有人知道该怎么做吗?

例如

this.stringProperty =“ string”在XAML标记中。

或伪代码

{RelativeSource Self} .stringProperty =“ string”

谢谢

@TRS

让我通过使用您的代码进行澄清。我只需要代码的第一部分。

public partial class MainWindow : Window <-- YOUR CODE
{

   private testString;  <-- ADDED THIS

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyClass(); <-- REMOVED THIS

    public string TestString;    <-- ADDED THIS
    {
        get => testString;  
        set
        {
         testString;   = value;
        }
    }
}

现在,我想从相同的局部类的MainWindow XAML中设置“ TestString”属性。

<Window x:Class="WpfApp6.MainWindow"
x:Name="Mywindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp6"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">

SET TestString PROPERTY IN THE CODE BEHIND HERE IN THE XAML

因此,请牢记这一点。我该怎么办?

1 个答案:

答案 0 :(得分:0)

这是为您提供的最小工作示例。但是,您必须阅读有关DataContext,INotifyPropertyChanged和MVVM的内容才能全面了解它,否则您将有很多疑问。请保持代码干净。

<Window x:Class="WpfApp6.MainWindow"
    x:Name="Mywindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp6"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <TextBlock Text="{Binding MyString}"></TextBlock>

</Grid>

和后面的代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MyClass();
    }
}

public class MyClass : INotifyPropertyChanged
{
    private string _myString;

    public string MyString
    {
        get => _myString;
        set
        {
            _myString = value;
            OnPropertyChanged();
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}