簡體   English   中英

C#XAML設置器值設置為True,具體取決於字符串屬性值

[英]C# XAML Setter value to True depending on string property value

我在看似相當簡單的任務上遇到了麻煩。 我有一個帶有節點的樹視圖,如果我的視圖模型的特定字符串屬性“ SearchTerm”不為空,我想將整個樹視圖的TreeViewItem'IsExpanded'屬性設置為True。 換句話說,如果字符串屬性不為null,則IsExpanded值應為True。 我已經在代碼隱藏中完成了此操作,但是為了簡潔起見,我更喜歡在XAML中執行此操作。

為了描述下面的代碼,我創建了一個轉換器,它將空字符串轉換為“ False”,將非空字符串轉換為“ True”。 在我的XAML中,當我嘗試從TreeView ItemContainerStyle中的viewmodel綁定字符串值時,我將此轉換器稱為。 看來轉換器甚至從未被解雇。

我的XAML(簡體):

<UserControl.Resources>
    <cv:ExpandNodesIfSearchConverter x:Key="ExpandAll">
    </cv:ExpandNodesIfSearchConverter>
</UserControl.Resources>

<TreeView Grid.Row="2" x:Name="myTreeView"
      ItemsSource="{Binding Sponsors}"
      SelectedItemChanged="TreeView_SelectedItemChanged" >

        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                 <!-- if SearchTerm is not null, use converter to set value to true and expand all nodes -->
                <Setter Property="IsExpanded" Value="{Binding Path=SearchTerm, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ExpandAll}}" />
            </Style>
        </TreeView.ItemContainerStyle>

        <!-- TreeView data -->

    </TreeView>

我的視圖模型:

public class TreeViewVM : INotifyPropertyChanged
{
    private string _searchterm;
    public string SearchTerm
    {
        get
        {
            return _searchterm;
        }
        set
        {
            _searchterm = value;
            OnPropertyChanged("SearchTerm");
        }
    }
}

我的轉換器:

class ExpandNodesIfSearchConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //if searchterm is not null, return true to expand all items, otherwise return false
        string searchterm = value.ToString();
        if (string.IsNullOrEmpty(searchterm))
            return false;
        else
            return true;
    }

    public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我通過在Setter標記中使用ElementName而不是viewmodel屬性解決了我的問題。 searchTxt是SeachTerm綁定到的TextBox的名稱。

<Setter Property="IsExpanded" Value="{Binding ElementName=searchTxt, Path=Text, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ExpandAll}}" />

暫無
暫無

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

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