我有一个奇怪的情况,我在WPF窗口中绑定了一个转换器。有时,此窗口的内容将从所述窗口中删除并插入选项卡式窗口,如下所示:
public void AddNewTab(Window wpfWindow, String tabTitle, OnFocusHandler onFocusHandler)
{
//Unhook window contents
object content= wpfWindow.Content;
wpfWindow.Content = null;
//Create a new tab
TabItem newTab = new TabItem();
newTab.Header = title;
newTab.Style = (Style)Resources["CorsairTab"];
//newTab.Foreground = Brushes.White;
newTab.Background = Brushes.Transparent;
newTab.Content = content;
//Add it
TabControl.Items.Add(newTab);
//Tie handler if it exists
if (onFocusHandler != null)
_listOnTabSelectedEventHandlers.Add(onFocusHandler);
else
_listOnTabSelectedEventHandlers.Add(null);
//If this is the first tab, make it the opened one
if(TabControl.Items.Count == 1)
TabControl.SelectedIndex = 0;
}
所以这一切都很好,但是当有问题的内容剥离窗口与转换器绑定时会出现问题。我编写了一个继承自MarkupExtension的转换器以避免StaticReferences。我的转换器看起来像这样
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BoolToVisibilityConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isWorking = (bool)value;
if (isWorking)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
引用它的XAML看起来像这样:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Grid.Column="1" Grid.Row="1" Visibility="{Binding Path=IsEye, Converter={inf:BoolToVisibilityConverter}}">
<TextBlock Text="Working Eye" VerticalAlignment="Top" Foreground="White" Margin="5,5,0,0"/>
<Button Content="Approve All" Command="{Binding ApproveAllTrades}"
Margin="5,0,0,0" Width="auto" Height="auto" VerticalAlignment="Top" Background="#DCDCDC"/>
</StackPanel>
<views:OrdersWorkingEyeView Loaded="EyeOrders_Loaded" Grid.Column="1" Grid.Row="2" Visibility="{Binding Path=IsEye, Converter={inf:BoolToVisibilityConverter}}"/>
忽略BoolToVisibility已经定义的那一刻,当我剥离其内容的窗口并加载这两个特定控件(一个由我定义,另一个是堆栈面板)时,在ProvideValue设置的断点点击两次(对于每个控件一次),但转换只调用一次,用于我的自定义控件。结果是自定义控件具有适当的可见性,但堆栈面板却没有。我很确定绑定本身是有效的,因为两个控件上绑定的路径是相同的,并且适用于自定义控件。我无法弄清楚是什么区别导致转换发生在一个而不是另一个(或者,也许,为什么它没有正确绑定StackPanel)。帮助
修改的
对于它的价值,当我不将内容从窗口中剥离并将其放入新的TabItem时,一切都有效。可见性更新并显示正常。
答案 0 :(得分:0)
我尝试过您的示例,并进行了以下更改以使其正常工作
private bool _isEye= true;
public bool IsEye
{
get { return _isEye; }
set { _isEye = value;
NotifyFropertyChanged("IsEye");
}
}
定义资源
<Window.Resources>
<!-- local is your namespace-->
<local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
</Window.Resources>
更新绑定
Visibility="{Binding Path=IsEye,Converter={StaticResource BoolToVisibilityConverter}}"
并且它适用于usercontrol和stackpanel。 希望这可能有所帮助。