簡體   English   中英

如何將文本框綁定到WPF中的類的字段?

[英]How to bind TextBox to field of a class in WPF?

我正在嘗試為矢量值創建一個自定義屬性編輯器,如下所示:

 public struct Float4
 {
      public float x,y,z,w;
 }

在某些對象中,它將具有如下屬性:

public class SomeEntity : INotifyPropertyChanged
{
      private Float4 prop;
      [Category("Property")]
      [Editor(typeof(VectorEditor),typeof(PropertyValueEditor)]
      public Float4 Prop
      {
            get{return prop;}
            set{prop = value ; NotifyPropertyChanged("prop");}
      }  
}

(我從這里開始使用WpfPropertyGrid)

VectorEditor使用如下數據VectorEditor

<DataTemplate x:Key="VectorEditorTemplate">
    <DataTemplate.Resources>
        <!--first use a ObjectDataProvider to get a `Type`-->
        <ObjectDataProvider MethodName="GetType" ObjectType="{x:Type local:Float4}" x:Key='VectorType' >
        </ObjectDataProvider>
        <local:GetFieldsConverter x:Key="GetFieldsConverter" />
    </DataTemplate.Resources>         

    <!--then use a Converter to create a ObservableCollection of `FieldInfo` from `Type`-->
    <ItemsControl ItemsSource="{Binding Source={StaticResource VectorType},Converter={StaticResource GetFieldsConverter}}">
            <ItemsControl.Resources>
            <!-- this Converter will provider field name-->
                <local:GetFieldNameConverter x:Key="GetFieldNameConverter"/>
            </ItemsControl.Resources>
            <!-- Other Elements -->
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <DockPanel HorizontalAlignment="Stretch">
                        <TextBlock DockPanel.Dock='Left' Text="{Binding Converter={StaticResource GetFieldNameConverter}}" Width="25" />
                        <TextBox HorizontalAlignment="Stretch" Text="{Binding Path=Value}"/>
                    </DockPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
</DataTemplate>

在這種情況下,TextBox.Text中的Path設置為Value ,因為它是模板,所以它不知道此Item與哪個字段關聯。

那么,如何使其與現場相關聯? 並綁定到它,因此,當此TextBox的值更改時,它可以向包含Float4的對象引發PropertyChanged事件。

至少有兩件事會阻止在WPF中使用Float4類型:

  • 這是一種價值類型

  • 成員不是屬性而是字段

因此,我擔心您將不得不使用代理服務器來實現您的價值觀:

public class Float4Proxy : INotifyPropertyChanged
{
    private Float4 float4;

    public float X
    {
        get { return float4.x; }
        set
        {
            if (value != float4.x)
            {
                float4.x = value;
                PropertyChanged(this, new PropertyChangedEventArgs("X"));
            }
        }
    }

    ...
}

在您的XAML中,您將能夠進行以下兩種方式的綁定:

<TextBox HorizontalAlignment="Stretch" Text="{Binding Path=Value.X}"/>

暫無
暫無

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

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