Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当通过代码设置条件属性时,wpf应用程序中未设置按钮背景颜色_C#_Wpf_Xaml_User Controls - Fatal编程技术网

C# 当通过代码设置条件属性时,wpf应用程序中未设置按钮背景颜色

C# 当通过代码设置条件属性时,wpf应用程序中未设置按钮背景颜色,c#,wpf,xaml,user-controls,C#,Wpf,Xaml,User Controls,我的一个用户控件中有一个按钮,需要根据属性集更改其背景。无论设置了什么属性值(true或false),背景色都不会更改。我甚至注意到在调试期间,property的值被设置为true,但没有触发触发器来设置背景色 <UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class

我的一个用户控件中有一个按钮,需要根据属性集更改其背景。无论设置了什么属性值(true或false),背景色都不会更改。我甚至注意到在调试期间,property的值被设置为true,但没有触发触发器来设置背景色

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.SubToolbar"
x:Name="SubToolBar" Width="Auto" Height="Auto" HorizontalAlignment="Stretch" DataContext="{Binding RelativeSource={RelativeSource Self}}"
>

<UserControl.Resources>
    <Style x:Key="MyFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Control}">
                    <Grid Margin="8">
                        <Ellipse  Name="r1" Stroke="Black" StrokeDashArray="2 2" StrokeThickness="1"/>
                        <Border Name="border"  Width="{TemplateBinding ActualWidth}" Height="{TemplateBinding ActualHeight}" BorderThickness="1" CornerRadius="2"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="CircleButton" TargetType="Button">

        <Setter Property="Background" Value="{ Binding Path= Background12,   RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWay}"/>


        <Style.Triggers>

            <DataTrigger Binding="{Binding RiskHighLowMedium }"  Value="True">
                <Setter Property="Background" Value="{ Binding Path= Background12,   RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWay}"/>
            </DataTrigger>

        </Style.Triggers>

    </Style>
</UserControl.Resources>


 <Border Background="#FFD4BFAE" CornerRadius="5" >
<Grid x:Name="LayoutRoot" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="50"/>
        </Grid.ColumnDefinitions>

        <TextBox  Grid.Column="0"  Padding="5" Text="{Binding  Path=ID}"/>
        <TextBox  Grid.Column="1" Margin="2,0,0,0" Padding="5" Text="{Binding  Path=Name}"/>

        <Button Name="highLowRisk" Padding="5" Grid.Column="2" Width="30" Height="30" Style="{StaticResource CircleButton}" Margin="5,5,5,5" />







    </Grid>
 </Border>

我在xaml文件中这样设置样式模板。

但似乎没有什么改变背景颜色

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.SubToolbar"
x:Name="SubToolBar" Width="Auto" Height="Auto" HorizontalAlignment="Stretch" DataContext="{Binding RelativeSource={RelativeSource Self}}"
>

<UserControl.Resources>
    <Style x:Key="MyFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Control}">
                    <Grid Margin="8">
                        <Ellipse  Name="r1" Stroke="Black" StrokeDashArray="2 2" StrokeThickness="1"/>
                        <Border Name="border"  Width="{TemplateBinding ActualWidth}" Height="{TemplateBinding ActualHeight}" BorderThickness="1" CornerRadius="2"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="CircleButton" TargetType="Button">

        <Setter Property="Background" Value="{ Binding Path= Background12,   RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWay}"/>


        <Style.Triggers>

            <DataTrigger Binding="{Binding RiskHighLowMedium }"  Value="True">
                <Setter Property="Background" Value="{ Binding Path= Background12,   RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Mode=OneWay}"/>
            </DataTrigger>

        </Style.Triggers>

    </Style>
</UserControl.Resources>


 <Border Background="#FFD4BFAE" CornerRadius="5" >
<Grid x:Name="LayoutRoot" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="60"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="50"/>
        </Grid.ColumnDefinitions>

        <TextBox  Grid.Column="0"  Padding="5" Text="{Binding  Path=ID}"/>
        <TextBox  Grid.Column="1" Margin="2,0,0,0" Padding="5" Text="{Binding  Path=Name}"/>

        <Button Name="highLowRisk" Padding="5" Grid.Column="2" Width="30" Height="30" Style="{StaticResource CircleButton}" Margin="5,5,5,5" />







    </Grid>
 </Border>
下面的代码是

/// <summary>
/// Interaction logic for SubToolbar.xaml
/// </summary>
public partial class SubToolbar : UserControl, INotifyPropertyChanged
{
    /// <summary>
    /// default ctor
    /// </summary>
    public SubToolbar()
    {
        DataContext = this;
        InitializeComponent();
    }


    /// <summary>
    /// setting whethere 
    /// risk is high or low
    /// </summary>
    /// <param name="_riskhighLow"></param>
    public void SetRiskHighLow(bool _riskhighLow)
    {
        _riskHighLowMedium = _riskhighLow;
        this.OnPropertyChanged("RiskHighLowMedium");
        this.OnPropertyChanged("Background12");

    }

    /// <summary>
    /// RiskHighLowMedium
    /// </summary>

    private bool _riskHighLowMedium;

    /// <summary>
    /// property to set risk high
    /// low and medium
    /// </summary>
    public bool RiskHighLowMedium
    {
        get { return _riskHighLowMedium; }
        set
        {
                _riskHighLowMedium = value;

                this.OnPropertyChanged("RiskHighLowMedium");
                this.OnPropertyChanged("Background12");

        }
    }



    /// <summary>
    /// background property
    /// to set button background
    /// color
    /// </summary>
    public Brush Background12
    {
        get
        {
            return RiskHighLowMedium ? Brushes.Red : Brushes.Blue;

        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {

        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion // INotifyPropertyChanged Members




}
//
///subtolbar.xaml的交互逻辑
/// 
公共分部类子工具栏:UserControl,INotifyPropertyChanged
{
/// 
///默认选择器
/// 
公共副工具栏()
{
DataContext=this;
初始化组件();
}
/// 
///在那里设置
///风险是高还是低
/// 
/// 
公共无效设置风险高低(bool\u riskhailow)
{
_riskHighLowMedium=\u riskhighLow;
本条对不动产进行了变更(“风险高-低-中”);
本条关于财产变更(“背景12”);
}
/// 
///风险高低中
/// 
私人布尔(highlowmedium),;
/// 
///房地产将设定高风险
///中低
/// 
公共布尔风险高-低-中
{
获取{return\u riskhailowmedium;}
设置
{
_风险高-低-中=价值;
本条对不动产进行了变更(“风险高-低-中”);
本条关于财产变更(“背景12”);
}
}
/// 
///背景属性
///设置按钮背景
///颜色
/// 
公开背景12
{
得到
{
返回RiskHighLowMedium?画笔。红色:画笔。蓝色;
}
}
#区域INotifyProperty更改成员
公共事件属性更改事件处理程序属性更改;
受保护的虚拟void OnPropertyChanged(字符串propertyName)
{
if(this.PropertyChanged!=null)
this.PropertyChanged(this,newpropertychangedventargs(propertyName));
}
#endregion//INotifyPropertyChanged成员
}

此处不需要
DataTrigger
,因为您不需要更改其setter中的任何内容。您还必须为
背景
筹集
属性更改
,并使用
风险高低中

        public bool RiskHighLowMedium
        {
            get { return _riskHighLowMedium; }
            set
            {
                    _riskHighLowMedium = value;
                    this.OnPropertyChanged("RiskHighLowMedium");
                    this.OnPropertyChanged("Background12");
            }
        }
在xaml中

     <Button Name="highLowRisk" Padding="5" Grid.Column="2" Width="30" Height="30" Background={Binding Background12} Margin="5,5,5,5" />

希望这有帮助

  public partial class MainWindow : Window
{
    private ExampleViewModel m_ViewModel;
    public MainWindow()
    {
        InitializeComponent();
        m_ViewModel = new ExampleViewModel();
        this.DataContext = m_ViewModel;
    }

    private void btn_Click(object sender, RoutedEventArgs e)
    {
        m_ViewModel.RiskHighLowMedium = true;
    }
}

public class ExampleViewModel : INotifyPropertyChanged
{
    private bool _riskHighLowMedium = false;
    public ExampleViewModel()
    {

    }

    public bool RiskHighLowMedium
    {
        get 
        { 
            return _riskHighLowMedium; 
        }
        set
        {
            _riskHighLowMedium = value;
            OnPropertyChanged("RiskHighLowMedium");
        }
    }

    public Brush Background
    {
        get
        {
            return RiskHighLowMedium ? Brushes.Red : Brushes.Blue;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

 <Style x:Key="CircleButtonStyle" TargetType="Button">
        <Setter Property="Background" Value="{Binding Path=Background, Mode=OneWay}"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding RiskHighLowMedium}"  Value="True">
                <Setter Property="Background" Value="{ Binding Path= Background, Mode=OneWay}"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

  <Grid>
    <Button Name="btn" Height="40" Width="180" Content="Hello" Style="{StaticResource CircleButtonStyle}" Click="btn_Click"></Button>
</Grid>
公共部分类主窗口:窗口
{
私有示例ViewModel m_ViewModel;
公共主窗口()
{
初始化组件();
m_ViewModel=新示例ViewModel();
this.DataContext=m_ViewModel;
}
私有无效btn_单击(对象发送方,路由目标)
{
m_ViewModel.RiskHighLowMedium=true;
}
}
公共类示例ViewModel:INotifyPropertyChanged
{
private bool_riskHighLowMedium=假;
公共示例ViewModel()
{
}
公共布尔风险高-低-中
{
得到
{ 
返回riskHighLowMedium;
}
设置
{
_风险高-低-中=价值;
不动产变更(“风险高-低-中”);
}
}
公共画笔背景
{
得到
{
返回RiskHighLowMedium?画笔。红色:画笔。蓝色;
}
}
公共事件属性更改事件处理程序属性更改;
受保护的无效OnPropertyChanged(字符串propertyName)
{
if(this.PropertyChanged!=null)
{
PropertyChanged(这是新的PropertyChangedEventArgs(propertyName));
}
}
}

我想您可能需要一些转换器。更多信息:酒店在哪里?它们是在UserControl上还是在ViewModel上?这是在特定条件下设置的属性,无论该条件是true还是false。这些属性在usercontrol上。首先,您的代码对我来说可以正常工作。第二,从哪里执行属性的更新?第三,最好对控件上的所有属性使用DependencyProperty。。但是用户界面上的按钮颜色没有这样的变化。您是否将UI的DataContext设置为self?这很奇怪。。背景加载的默认值是否正确,即画笔。启动时出现蓝色?是,默认值正确。但是关于财产的变化。。颜色没有改变吗?我正在尝试,但没有任何帮助:(你能在应用这种风格的地方分享按钮xaml吗