簡體   English   中英

WPF Expander IsExpanded綁定

[英]WPF Expander IsExpanded binding

我有一個Expander控件,其IsExpanded屬性綁定到mvvm模型中的bool。 綁定工作正常,直到你不接觸擴展器。 單擊擴展器中的箭頭以展開后,綁定將停止工作。 在模型中將bool ShowPreview設置為false不會折疊展開器。

<Expander Name="pExpander" 
          IsExpanded="{Binding Path=ShowPreview,Mode=OneWay}"
          Header="Preview">
    <TextBlock Text="{Binding Path=Message, Mode=OneWay}"></TextBlock>    
</Expander>

如果您刪除Mode=OneWay確實可以解決問題嗎?

在讀取其他CTQ(對GUI的更改不影響模型)時,我沒有很好的建議如何限制底層數據看到的更改。 有什么區別:

myModel.MyProperty = true; // in *your* code behind

myModel.MyProperty = true; // done by a binding

讓我感到IsExpandedIsExpanded默認是OneWay ,所以

<Style TargetType="TreeViewItem">
    <Setter Property="IsExpanded" Value="{Binding Expanded}"/>
</Style>

不按我預期的方式工作。 只有當你添加Mode=TwoWay ,它才有效(即項目開始關注我的Expanded屬性,並更新它),如

<Style TargetType="TreeViewItem">
    <Setter Property="IsExpanded" Value="{Binding Expanded, Mode=TwoWay}"/>
</Style>

使用Silverlight我這樣做:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

<Expander Name="pExpander" IsExpanded="True" Header="Preview">
    <i:Interaction.Triggers>
        <ei:PropertyChangedTrigger Binding="{Binding ShowPreview, Mode=OneWay}">
            <ei:ChangePropertyAction PropertyName="IsExpanded" Value="{Binding ShowPreview, Mode=OneWay}"/>
        </ei:PropertyChangedTrigger>
    </i:Interaction.Triggers>
    <TextBlock Text="{Binding Path=Message, Mode=OneWay}"></TextBlock>    
</Expander>
<Expander Name="pExpander1" IsExpanded="True" Header="Preview 1">
    <i:Interaction.Triggers>
        <ei:PropertyChangedTrigger Binding="{Binding ShowPreview, Mode=OneWay}">
            <ei:ChangePropertyAction PropertyName="IsExpanded" Value="{Binding ShowPreview, Mode=OneWay}"/>
        </ei:PropertyChangedTrigger>
    </i:Interaction.Triggers>
    <TextBlock Text="{Binding Path=Message1, Mode=OneWay}"></TextBlock>    
</Expander>
//...

當你手動擴展/折疊一個Expander時,綁定不會丟失......

做三件事,

確保您的ViewModel正在實現INotifyPropertyChanged 如果您的視圖模型在屬性更改時未通知您,您的ui將不會知道更改

將模式更改為TwoWay ,您希望在擴展器更改時更新視圖模型,並且希望在視圖模型更改時更新擴展器

最后,如果以上兩個不起作用,請使用調試轉換器來確定綁定是否失敗。 有一個例子在這里的如何做到這一點。 這是每個wpf開發人員需要的技術。

我知道單選按鈕存在問題,當組中的另一個按鈕被設置時,它們會丟失綁定,我不認為這是問題,但是調試轉換器將幫助您解決這個問題。

暫無
暫無

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

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