【问题标题】:wpf how to get value from textbook in ControlTemplate treeivwitemwpf如何从ControlTemplate treeivwitem中的教科书中获取价值
【发布时间】:2019-04-19 17:13:57
【问题描述】:

如何获取txt_add.text 值? 这种风格适用于代码后面的TreeViewitem

<Page.Resources>
    <Style TargetType="{x:Type TreeViewItem}" x:Key="add" >
        <Setter Property="Background" Value="{DynamicResource WhiteBrush}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TreeViewItem" >
                    <StackPanel Orientation="Horizontal" Margin="5">
                        <TextBox Width="300" Controls:TextBoxHelper.Watermark="Account Name" Margin="2" x:Name="txt_add"/>
                        <Button Content="{x:Static lang:ResLang.insert}" Style="{StaticResource ButtonSystem}" Width="100" Margin="2" Click="Button_AddNewSubOk_Click"/>
                        <Button Content="{x:Static lang:ResLang.btn_cancel}" Style="{StaticResource ButtonCancel }" Width="100" Margin="2" Click="Button_AddNewSubCancel_Click"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>
</Page>

【问题讨论】:

    标签: wpf templates controls treeviewitem


    【解决方案1】:

    您需要使用 mvvm 模式绑定它,创建一个继承 inotifypropertychanged 的​​视图模型类,然后将您的文本绑定到该类中的属性。

    <Window.DataContext>
        <model:viewmodel x:Key="viewmodel"/>
    </Window.DataContext>
    <!-- where ever you got your textbox -->
    <TextBox Text="{Binding Mode=TwoWay,Source={StaticResource viewmodel},Path=stringproperty"/>  
    

    和简单的视图模型类:

    public class viewmodel : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            [NotifyPropertyChangedInvocator]
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            public String stringproperty{ get; set; } ;
        }  
    

    如果这不适合您,可以在 Web 中简单地实现“属性已更改”。
    你可以像这样访问它,但这是错误的,你不应该这样做

    (this.DataContext as viewmodel).stringproperty
    

    绑定后仅使用绑定来访问您的数据,如果您在某些操作或事件中需要它们作为参数传递给“命令”,您可以搜索一下

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-17
      • 2019-12-26
      • 1970-01-01
      • 2017-10-01
      • 2018-04-07
      • 2021-12-26
      • 1970-01-01
      • 2016-08-24
      相关资源
      最近更新 更多