我環顧四周,但仍然無法找到解決的辦法......用戶控件綁定到的ObservableCollection不工作
我做了一個UserControl
這基本上是一個滑塊,但幾乎沒有自定義功能。
public partial class CustomSlider : UserControl
{
public CustomSlider()
{
InitializeComponent();
this.DataContext = this;
CMiXSlider.ApplyTemplate();
Thumb thumb0 = (CMiXSlider.Template.FindName("PART_Track", CMiXSlider) as Track).Thumb;
thumb0.MouseEnter += new MouseEventHandler(thumb_MouseEnter);
}
private void thumb_MouseEnter(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && e.MouseDevice.Captured == null)
{
MouseButtonEventArgs args = new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, MouseButton.Left);
args.RoutedEvent = MouseLeftButtonDownEvent;
(sender as Thumb).RaiseEvent(args);
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(double), typeof(CustomSlider), new PropertyMetadata(0.0));
public double Value
{
get { return (double)this.GetValue(ValueProperty); }
set { this.SetValue(ValueProperty, value); }
}
}
的XAML:
<UserControl x:Class="CMiX.CustomSlider"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CMiX"
mc:Ignorable="d"
d:DesignHeight="139.8" d:DesignWidth="546.2">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/CMiX_UserControl;component/RessourceDictionnaries/Brushes/GenericBrushes.xaml"/>
<ResourceDictionary Source="/CMiX_UserControl;component/RessourceDictionnaries/Styles/BaseSliderStyle.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Slider x:Name="CMiXSlider" Style="{StaticResource BaseSliderStyle}"
Value="{Binding Value, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type local:CustomSlider}}}"
IsMoveToPointEnabled="True" Minimum="0.0" Maximum="1.0"/>
</Grid>
然後我用這裏面的另一個UserControl
像這樣:
<CMiX:CustomSlider x:Name="SliderTest" Grid.Row="2" Value="{Binding ChannelsAlpha[0], Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
而且我試圖綁定到這個ObservableCollection
(中相同的滑塊將被使用6次):
private ObservableCollection<double> _ChannelsAlpha = new ObservableCollection<double>(new[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 });
public ObservableCollection<double> ChannelsAlpha
{
get { return _ChannelsAlpha; }
set { _ChannelsAlpha = value; }
}
問題是,綁定不會以任何方式發生。而我特別沒有得到的是,如果我使用這個標準滑塊:
<Slider x:Name="Ch0_Alpha" Margin="1" IsMoveToPointEnabled="True" Minimum="0.0" Maximum="1.0" Orientation="Horizontal" Value="{Binding DataContext.ChannelsAlpha[0], ElementName=Ch0_Alpha, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
然後它按預期工作。
在一個用戶控件中,initializecomponent應用模板,所以它不會改變任何東西。 – briantyler
@briantyler這就是爲什麼我說「爲了好形式」。 –
好的一切工作正常,謝謝我學習新的東西。但是,你介意告訴我更多爲什麼this.DataContext = this;打破了數據上下文。我認爲我正在定義它......謝謝 – lecloneur