【问题标题】:Update property from MainWindow to userControl将属性从 MainWindow 更新为 userControl
【发布时间】:2014-02-19 10:39:14
【问题描述】:

我在 MainWindow "ZoomSlider" 中定义了属性,即数据绑定到 Slider

UserControl 上,我有一个Ellipse,它的高度限制为Slider 值。

主窗口代码

<Slider 
   Grid.Column="4"  
   Value="{Binding ElementName=MainWindow,Path=ZoomSlider,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}"
   Maximum="46" 
   Minimum=".1" 
   LargeChange=".1" 
   Ticks="0,1,5" 
   TickPlacement="BottomRight" 
   SmallChange=".1" 
   Height="22"  
   Width="75" 
   Margin="0" 
   HorizontalAlignment="Right" 
   VerticalAlignment="Bottom">
</Slider>

<!--Content Control is the Host of a userControl which iam Setting dynamically at runtime-->

<ContentControl Name="content" BorderThickness="1"  

Content="{Binding CurrentViewModel,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}">     

</ContentControl>

用户控制代码

<Ellipse  Stroke="Black">
   <Ellipse.Height>
      <MultiBinding Converter="{StaticResource zoomConverter}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnSourceUpdated="True">

           <Binding Path="Dia" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnSourceUpdated="True"/>

           <Binding RelativeSource="{RelativeSource FindAncestor,AncestorType={x:Type Window}}" Path="ZoomSlider" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" 
         NotifyOnSourceUpdated="True" PresentationTraceSources.TraceLevel="High"/>

      </MultiBinding> 

MainWindow c# 代码

private double zoomSlider = 2;

public double ZoomSlider
{
    get { return zoomSlider; }
    set
    {
        zoomSlider = value;
        NotifyPropertyChanged("ZoomSlider");
    }
}

我成功获得了UserControl 中的默认滑块值,但是当Slider 的 value 属性发生更改时,它不会反映在UserControl 中。

那么,底线如何将更新后的滑块值设为UserControl Ellipse

注意:

UserControl 绑定到 UserControl Viewmodel,MainWindow 绑定到 Window ViewModel

感谢任何帮助!!!!

【问题讨论】:

  • 在此处放置转换器&lt;Binding RelativeSource="{RelativeSource FindAncestor,AncestorType={x:Type Window}}" Path="ZoomSlider" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnSourceUpdated="True" PresentationTraceSources.TraceLevel="High"/&gt; 并检查...

标签: c# wpf user-controls inotifypropertychanged


【解决方案1】:

ZoomSlider 应该有一个 DependencyProperty 作为支持字段以启用绑定

public double ZoomSlider
{
   get { return (double)GetValue(ZoomSliderProperty); }
   set { SetValue(ZoomSliderProperty, value); }
}

// Using a DependencyProperty as the backing store for ZoomSlider.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty ZoomSliderProperty =
            DependencyProperty.Register("ZoomSlider", typeof(double), typeof(MainWindow), new PropertyMetadata(2d));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2021-04-21
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多